Does allocating cooperative individuals to high-degree nodes prevent isolation?

round = NULL
gameID = NULL 
nodes = NULL
meanDegree = NULL
meanDegreeCoop = NULL #mean degree among those who cooperated
meanDegreeDefect = NULL #mean degree among those who defected
meanDist = NULL #mean shortest path length divided by the maximum possible path length (Nvertices - 1)
maxDist = NULL #max shortest path length divided by the maximum possible path length (Nvertices - 1)
coefGlobal = NULL #global clustering coefficient
percentCoop = NULL #proportion of those who cooperated
percentCoopPopular = NULL #proportion of those who cooperated, among those with degree >=10
coopEnv = NULL 
assort = NULL

for(i in 1:length(g.isolation)){
    round[i] =  mean(V(g.isolation[[i]])$round)
    gameID[i] = V(g.isolation[[i]])$gameID[1]
    nodes[i] = vcount(g.isolation[[i]])
    meanDegree[i] = mean(igraph::degree(g.isolation[[i]]),na.rm=TRUE)
    meanDegreeCoop[i] = mean(igraph::degree(g.isolation[[i]])[V(g.isolation[[i]])$behavior=="C"],na.rm=TRUE)
    meanDegreeDefect[i] = mean(igraph::degree(g.isolation[[i]])[V(g.isolation[[i]])$behavior=="D"],na.rm=TRUE)
    meanDist[i] = mean(distances(g.isolation[[i]])[distances(g.isolation[[i]])!=0 & distances(g.isolation[[i]])!=Inf],na.rm=TRUE) / length(V(g.isolation[[i]])-1)
    maxDist[i] = max(distances(g.isolation[[i]])[distances(g.isolation[[i]])!=0 & distances(g.isolation[[i]])!=Inf],na.rm=TRUE) / length(V(g.isolation[[i]])-1)
    coefGlobal[i] = transitivity(g.isolation[[i]], type="global")
    percentCoop[i] = prop.table(table(V(g.isolation[[i]])$behavior))["C"]
    percentCoopPopular[i] = prop.table(table(V(g.isolation[[i]])$behavior[igraph::degree(g.isolation[[i]])>=6]))["C"]
    coopEnv[i] = sum(ifelse(V(g.isolation[[i]])$behavior=="C",1,0)*igraph::degree(g.isolation[[i]])/sum(igraph::degree(g.isolation[[i]])),na.rm=TRUE)
    assort[i] = assortativity(g.isolation[[i]], V(g.isolation[[i]])$behavior == "C")
}

smallWorld = data.frame(
  round = round,
  gameID = gameID,
  nodes = nodes,
  meanDegree = meanDegree,
  meanDegreeCoop = meanDegreeCoop,
  meanDegreeDefect = meanDegreeDefect,
  diffDegreeCD = meanDegreeCoop - meanDegreeDefect,
  meanDist = meanDist,
  maxDist = maxDist,
  coefGlobal = coefGlobal,
  percentCoop = percentCoop,
  percentCoopPopular = percentCoopPopular,
  coopEnv = coopEnv,
  assort = assort
)


round = NULL
gameID = NULL
visibleWealth = NULL
n=1
for(i in unique(cdata$round)){
  for(m in unique(cdata$gameID)){
    round[n] = as.numeric(i)-1
    gameID[n] = m
    visibleWealth[n] = ifelse(cdata[cdata$round==i & cdata$gameID==m,]$showScore[1]=="true",1,0)
    n=n+1
  }
}

smallWorld.2 = data.frame(
  round = round,
  gameID = gameID,
  visibleWealth = visibleWealth
)

smallWorld = merge(smallWorld, smallWorld.2, by=c("gameID","round"), all.x=TRUE)

smallWorld.initial = subset(smallWorld, smallWorld$round==0)

#percent of people that end up being isolated for each gameID
percentIsolated = NULL
percentIsolated = aggregate(isolated ~ gameID, data=sample.wide, FUN=max, na.rm=TRUE)
smallWorld.initial = merge(smallWorld.initial[c("gameID","meanDegree","meanDegreeCoop","meanDegreeDefect","diffDegreeCD","meanDist","coefGlobal","visibleWealth","percentCoop","percentCoopPopular","coopEnv","assort")],percentIsolated, by="gameID", all.x=TRUE)

percentIsolated = NULL
percentIsolated = aggregate(isolated ~ gameID, data=sample.wide, FUN=mean, na.rm=TRUE)
percentIsolated = percentIsolated %>% rename(
  percentIsolated = isolated
)
smallWorld.initial = merge(smallWorld.initial,percentIsolated, by="gameID", all.x=TRUE)




reg = glm(isolated ~ coopEnv, 
      data = smallWorld.initial,
      family = binomial(link = "logit"))
summary(reg)
## 
## Call:
## glm(formula = isolated ~ coopEnv, family = binomial(link = "logit"), 
##     data = smallWorld.initial)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.3756   0.2641   0.4839   0.6926   1.3696  
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)    
## (Intercept)    6.047      1.734   3.487 0.000489 ***
## coopEnv       -6.813      2.351  -2.898 0.003750 ** 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 82.760  on 79  degrees of freedom
## Residual deviance: 72.371  on 78  degrees of freedom
## AIC: 76.371
## 
## Number of Fisher Scoring iterations: 5
reg = glm(isolated ~ coopEnv*percentCoop, 
      data = smallWorld.initial,
      family = binomial(link = "logit"))
summary(reg)
## 
## Call:
## glm(formula = isolated ~ coopEnv * percentCoop, family = binomial(link = "logit"), 
##     data = smallWorld.initial)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.2132   0.4220   0.4658   0.5862   1.7551  
## 
## Coefficients:
##                     Estimate Std. Error z value Pr(>|z|)
## (Intercept)           -3.096      6.866  -0.451    0.652
## coopEnv               10.481     12.639   0.829    0.407
## percentCoop           10.681     12.929   0.826    0.409
## coopEnv:percentCoop  -20.525     14.822  -1.385    0.166
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 82.760  on 79  degrees of freedom
## Residual deviance: 70.472  on 76  degrees of freedom
## AIC: 78.472
## 
## Number of Fisher Scoring iterations: 4
reg = glm(isolated ~ assort, 
      data = smallWorld.initial,
      family = binomial(link = "logit"))
summary(reg)
## 
## Call:
## glm(formula = isolated ~ assort, family = binomial(link = "logit"), 
##     data = smallWorld.initial)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -1.9579   0.5132   0.6439   0.7269   1.0178  
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)    
## (Intercept)   1.1349     0.3207   3.539 0.000402 ***
## assort       -3.7358     3.0781  -1.214 0.224862    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 67.731  on 64  degrees of freedom
## Residual deviance: 66.177  on 63  degrees of freedom
##   (15 observations deleted due to missingness)
## AIC: 70.177
## 
## Number of Fisher Scoring iterations: 4
reg = glm(isolated ~ assort*percentCoop, 
      data = smallWorld.initial,
      family = binomial(link = "logit"))
summary(reg)
## 
## Call:
## glm(formula = isolated ~ assort * percentCoop, family = binomial(link = "logit"), 
##     data = smallWorld.initial)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.5706   0.1873   0.4272   0.6978   1.3591  
## 
## Coefficients:
##                    Estimate Std. Error z value Pr(>|z|)   
## (Intercept)           6.695      2.392   2.799  0.00512 **
## assort              -23.388     22.419  -1.043  0.29684   
## percentCoop          -7.680      3.186  -2.411  0.01593 * 
## assort:percentCoop   25.842     29.451   0.877  0.38024   
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 67.731  on 64  degrees of freedom
## Residual deviance: 56.386  on 61  degrees of freedom
##   (15 observations deleted due to missingness)
## AIC: 64.386
## 
## Number of Fisher Scoring iterations: 5
reg = glm(percentIsolated ~ coopEnv, 
      data = smallWorld.initial, 
      family = gaussian(link = "identity"))
summary(reg)
## 
## Call:
## glm(formula = percentIsolated ~ coopEnv, family = gaussian(link = "identity"), 
##     data = smallWorld.initial)
## 
## Deviance Residuals: 
##      Min        1Q    Median        3Q       Max  
## -0.12622  -0.05564  -0.02541   0.03834   0.25903  
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  0.20852    0.04303   4.846 6.29e-06 ***
## coopEnv     -0.17058    0.06391  -2.669  0.00925 ** 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for gaussian family taken to be 0.006957149)
## 
##     Null deviance: 0.59222  on 79  degrees of freedom
## Residual deviance: 0.54266  on 78  degrees of freedom
## AIC: -166.43
## 
## Number of Fisher Scoring iterations: 2
reg = glm(percentIsolated ~ coopEnv*percentCoop, 
      data = smallWorld.initial, 
      family = gaussian(link = "identity"))
summary(reg)
## 
## Call:
## glm(formula = percentIsolated ~ coopEnv * percentCoop, family = gaussian(link = "identity"), 
##     data = smallWorld.initial)
## 
## Deviance Residuals: 
##      Min        1Q    Median        3Q       Max  
## -0.15277  -0.04970  -0.01807   0.03678   0.25172  
## 
## Coefficients:
##                     Estimate Std. Error t value Pr(>|t|)
## (Intercept)           0.1084     0.1925   0.563    0.575
## coopEnv               0.4950     0.3742   1.323    0.190
## percentCoop          -0.2223     0.3692  -0.602    0.549
## coopEnv:percentCoop  -0.3977     0.4417  -0.900    0.371
## 
## (Dispersion parameter for gaussian family taken to be 0.006743275)
## 
##     Null deviance: 0.59222  on 79  degrees of freedom
## Residual deviance: 0.51249  on 76  degrees of freedom
## AIC: -167.01
## 
## Number of Fisher Scoring iterations: 2
reg = glm(percentIsolated ~ assort, 
      data = smallWorld.initial, 
      family = gaussian(link = "identity"))
summary(reg)
## 
## Call:
## glm(formula = percentIsolated ~ assort, family = gaussian(link = "identity"), 
##     data = smallWorld.initial)
## 
## Deviance Residuals: 
##      Min        1Q    Median        3Q       Max  
## -0.13800  -0.04889  -0.01599   0.03676   0.29844  
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  0.08136    0.01164   6.988  2.1e-09 ***
## assort      -0.33980    0.09891  -3.435  0.00105 ** 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for gaussian family taken to be 0.006992089)
## 
##     Null deviance: 0.52302  on 64  degrees of freedom
## Residual deviance: 0.44050  on 63  degrees of freedom
##   (15 observations deleted due to missingness)
## AIC: -134.16
## 
## Number of Fisher Scoring iterations: 2
reg = glm(percentIsolated ~ assort*percentCoop, 
      data = smallWorld.initial, 
      family = gaussian(link = "identity"))
summary(reg)
## 
## Call:
## glm(formula = percentIsolated ~ assort * percentCoop, family = gaussian(link = "identity"), 
##     data = smallWorld.initial)
## 
## Deviance Residuals: 
##      Min        1Q    Median        3Q       Max  
## -0.13441  -0.04183  -0.01733   0.02556   0.27510  
## 
## Coefficients:
##                    Estimate Std. Error t value Pr(>|t|)    
## (Intercept)         0.22289    0.05970   3.733 0.000418 ***
## assort             -0.70774    0.42639  -1.660 0.102080    
## percentCoop        -0.20362    0.08504  -2.394 0.019731 *  
## assort:percentCoop  0.59881    0.63264   0.947 0.347615    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for gaussian family taken to be 0.006108948)
## 
##     Null deviance: 0.52302  on 64  degrees of freedom
## Residual deviance: 0.37265  on 61  degrees of freedom
##   (15 observations deleted due to missingness)
## AIC: -141.04
## 
## Number of Fisher Scoring iterations: 2
# #MSM
# # estimation of denominator of ip weights
# #cooperatorの数以外は全てRandom(Erdos-Renyi random graphにより決まるため)なので、coopEnvはpercentCoopで調整すれば十分か
# den.fit.obj <- lm(coopEnv ~ percentCoop + I(percentCoop^2), data = smallWorld.initial)
# p.den <- predict(den.fit.obj, type = "response")
# dens.den <- dnorm(smallWorld.initial$coopEnv, p.den, summary(den.fit.obj)$sigma)
# 
# # estimation of numerator of ip weights
# num.fit.obj <- lm(coopEnv ~ 1, data = smallWorld.initial)
# p.num <- predict(num.fit.obj, type = "response")
# dens.num <- dnorm(smallWorld.initial$coopEnv, p.num, summary(num.fit.obj)$sigma)
# 
# smallWorld.initial$sw.a = dens.num/dens.den
# summary(smallWorld.initial$sw.a)
# 
# msm.sw.cont <-geepack::geeglm(isolated ~ coopEnv, 
#                  data=smallWorld.initial, weights=sw.a, family = binomial(link="logit"), id=gameID, corstr="independence")
# summary(msm.sw.cont)
# 
# msm.sw.cont <-geepack::geeglm(percentIsolated ~ coopEnv, 
#                  data=smallWorld.initial, weights=sw.a, family = gaussian(link="identity"), id=gameID, corstr="independence")
# summary(msm.sw.cont)


ggplot(data = smallWorld.initial, aes(x = coopEnv, y = percentIsolated)) + 
  geom_point() +
  ggtitle("Percent isolated") +
  scale_x_continuous("Cooporative environment") +  
  scale_y_continuous("Percent of individuals isolated") + 
  scale_fill_continuous(type = "viridis")

ggplot(data = smallWorld.initial, aes(x = assort, y = percentIsolated)) + 
  geom_point() +
  ggtitle("Percent isolated") +
  scale_x_continuous("Assortativity coefficient of initial C/D") +  
  scale_y_continuous("Percent of individuals isolated") + 
  scale_fill_continuous(type = "viridis")
## Warning: Removed 15 rows containing missing values (`geom_point()`).

Simulation 1

All graphs start as Erdos-Renyi random newtorks

Cooperators have low degrees

#Define degrees of isolation
isolationDegree = 2

#number of iterations per arm
iterations = 500

modelForPrediction = "random forest" #"linear" or "random forest"

# List of manipulating parameters of experiments
#L : number of rounds
#V : Visible or not
#A : Income of a rich-group subject
#B : Income of a poor-group subject
#R : Probability to be assigned to a rich group
#I : Number of the same-parameter trial

R = 0.5
I = 0
L = 10


trends.df = data.frame()
  

  
  
for(A in c(1150,700,500)){
  for(V in c(0,1)){
      
      V = V
      A = A
      if(A==1150){B = 200} #high inequality
      if(A==700){B = 300} #low inequality
      if(A==500){B = 500} #no inequality
  
      if(modelForPrediction=="random forest"){
        source(paste(rootdir,"R/models.R",sep="/"))
        if(V==0){
          model1<-model1.invisible(redo=FALSE)
          model2<-model2.invisible(redo=FALSE)
          model3<-model3(redo=FALSE)
          }
        if(V==1){
          model1<-model1.visible(redo=FALSE)
          model2<-model2.visible(redo=FALSE)
          model3<-model3(redo=FALSE)
          }
      }
      
      df.netIntLowDegree = data.frame(
        coopFrac = NULL,
        avgCoop = NULL, 
        avgCoopFinal = NULL, 
        percentIsolation = NULL,
        isolation = NULL,
        percentIsolationC = NULL,
        percentIsolationD = NULL,
        nCommunities = NULL,
        communitySize = NULL,
        assortativityInitial = NULL,
        assortativityFinal = NULL,
        conversionRate = NULL,
        conversionToD = NULL, 
        conversionToC = NULL, 
        transitivity = NULL, 
        degree = NULL, 
        degreeC = NULL, 
        degreeD = NULL,
        meanConversionToD = NULL, 
        meanConversionToC = NULL, 
        degreeLost = NULL,
        degreeLostC = NULL,
        degreeLostD = NULL
      )
  
      #Here, factionCoop=0 will be the control: no rearranging of nodes will take place
      for(frac in c(0,0.25,0.5,0.75,1)){
        #nodes in the top fractionCoop degrees will automatically be a cooperator
        fractionCoop = frac
        
          coopFrac = NULL
          avgCoop = NULL
          homophilyC = NULL
          homophilyD = NULL
          heterophily = NULL
          avgCoopFinal = NULL
          percentIsolation = NULL
          isolation = NULL
          percentIsolationC = NULL
          percentIsolationD = NULL
          nCommunities = NULL
          communitySize = NULL
          assortativityInitial = NULL
          assortativityFinal = NULL
          conversionRate = NULL
          conversionToD = NULL 
          conversionToC = NULL
          transitivity = NULL
          degree = NULL
          degreeC = NULL
          degreeD = NULL
          meanConversionToD = NULL 
          meanConversionToC = NULL
          degreeLost = NULL
          degreeLostC = NULL
          degreeLostD = NULL
          avg_wealth = NULL
          gini = NULL
          for(m in c(1:iterations)){
            # Section 1. NOTES, packages, and Parameters
            #Importing library
            library(igraph) # for network graphing
            library(reldist) # for gini calculatio
            library(boot) # for inv.logit calculation
            #Two prefixed functions
            #rank
            rank1 = function(x) {rank(x,na.last=NA,ties.method="average")[1]} #a smaller value has a smaller rank.
            #gini mean difference (a.k.a. mean difference: please refer to https://stat.ethz.ch/pipermail/r-help/2003-April/032782.html)
            gmd = function(x) {
             x1 = na.omit(x)
             n = length(x1)
            tmp = 0
             for (i in 1:n) {
             for (j in 1:n) {
             tmp <- tmp + abs(x1[i]-x1[j])
             }
             }
            answer = tmp/(n*n)
             return(answer)
            }
        
            
            
            
            # List of fixed parameters of experiments (assumptions)
            #Rewiring rate = 0.3
            #GINI coefficient (can be known by A or B)
            GINI = 0*as.numeric(A==500) + 0.2*as.numeric(A %in% c(700,850)) + 0.4*as.numeric(A ==1150)
            #Collecting data frame (final output data frame)
            result = data.frame(round=0:L,n_par=NA,n_A=NA,avg_coop=NA,avg_degree=NA,avg_wealth=NA,gini=NA,gmd=NA,avg_coop_A=NA,avg_degree_A=NA,avg_wealth_A=NA,gini_A=NA,gmd_A=NA,avg_coop_B=NA,avg_degree_B=NA,avg_wealth_B=NA,gini_B=NA,gmd_B=NA,isolation=NA,percentIsolation=NA,meanConversionToD=NA,meanConversionToC=NA,degreeLost=NA,degreeLostC=NA,degreeLostD=NA)
            #_A is for a richer group and _B is for a poorer group
            
            
            #####################################################
            # Section 1.5: Practice rounds 1 to 2, to determine C/D in round 1
            
            N = 17 # median of the number of participants over rounds.
            node_rp0 = data.frame(ego_id=1:N, round=0)
            node_import = node_rp0
            
            for (k in 1:2){
              node_rX = node_import #Importing data
              node_rX$round = node_rX$round + 1
              node_rX[is.na(node_rX$prev_degree)==1,"prev_degree"] = 0
              node_rX[is.na(node_rX$prev_local_rate_coop)==1,"prev_local_rate_coop"] = 0
              #Only this calculation needs to change from Round 1
              if (k==1) {
                node_rX$prob_coop = inv.logit(1.099471) 
              } else {
                node_rX$prob_coop = inv.logit((-0.02339288) + (1.46068980)*as.numeric(node_rX$prev_coop==1))
              } 
              
              node_rX$coop = apply(data.frame(node_rX$prob_coop),1,function(x) {sample(1:0,1,prob=c(x,(1-x)))})
              
              node_rX$prev_coop = node_rX$coop
                
              assign(paste("coop_rp",k, sep=""),node_rX$coop)
              
              #For the loop
              node_import = node_rX
            }
            
            #cooperation rate in the practice rounds
            coop_rp = apply(cbind(coop_rp1,coop_rp2),1,mean)
      
            #####################################################
            # Section 2: Round 0 (Agents and environments)
            #Node data generation
            N = 17 # median of the number of participants over rounds.
            node_r0 = data.frame(ego_id=1:N, round=0)
            node_r0$coop_rp = ifelse(coop_rp==1,"C","D")
            node_r0$group = sample(c("rich","poor"),N,replace=TRUE,prob=c(R,1-R)) #R is defined as the probability to be assigned to the rich group
            node_r0$initial_wealth = ifelse(node_r0$group=="rich",A,B)
            #Link data generation
            ego_list = NULL
            for (i in 1:N) { ego_list = c(ego_list,rep(i,N)) }
            link_r0 = data.frame(ego_id=ego_list,alt_id=rep(1:N,N))
            link_r0 = link_r0[(link_r0$ego_id < link_r0$alt_id),] #The link was bidirectional, and thus the half and self are omitted.
            link_r0$connected = sample(0:1,dim(link_r0)[1],replace=TRUE,prob=c(0.7,0.3)) #Initial rewiring rate is fixed, 0.3
            link_r0c_ego = link_r0[link_r0$connected==1,]
            link_r0c_alt = link_r0[link_r0$connected==1,]
            colnames(link_r0c_alt) = c("alt_id","ego_id","connected")
            link_r0c = rbind(link_r0c_ego,link_r0c_alt) #this is bidirectional (double counted) for connected ties.
            link_r0c = link_r0c[order(link_r0c$ego_id),]
            link_r0c$alternumber = NA #putting the number for each alter in the same ego
            link_r0c[1,]$alternumber = 1
            for (i in 1:(dim(link_r0c)[1]-1))
              {if (link_r0c[i,]$ego_id == link_r0c[i+1,]$ego_id)
                {link_r0c[i+1,]$alternumber = link_r0c[i,]$alternumber + 1}
              else
                {link_r0c[i+1,]$alternumber = 1}
              #print(i)
              }
            link_r0c2 = reshape(link_r0c, direction = "wide", idvar=c("ego_id","connected"), timevar="alternumber")
            link_r0c2$initial_degree = apply(link_r0c2[,colnames(link_r0c2)[substr(colnames(link_r0c2),1,6) == "alt_id"]],1,function(x){length(na.omit(x))}) #Degree of each ego
            link_r0c2[is.na(link_r0c2$initial_degree)==1,"initial_degree"] = 0
            #Reflect the degree and initial local gini coefficient into the node data
            node_r0 = merge(x=node_r0,y=link_r0c2,all.x=TRUE,all.y=FALSE,by="ego_id")
            node_r0$initial_avg_env_wealth = NA
            node_r0$initial_local_gini = NA #local gini coefficient of the ego and connecting alters
            node_r0$initial_rel_rank = NA #local rank of ego among the ego and connecting alters (divided by the number of the go and connecting alters)
            for (i in 1:(dim(node_r0)[1])){
              node_r0[i,]$initial_avg_env_wealth = mean(na.omit(node_r0[node_r0$ego_id %in%
              node_r0[i,colnames(node_r0)[substr(colnames(node_r0),1,6) %in% c("ego_id","alt_id")]],"initial_wealth"]))
              node_r0[i,]$initial_local_gini = gini(na.omit(node_r0[node_r0$ego_id %in% node_r0[i,colnames(node_r0)[substr(colnames(node_r0),1,6)
              %in% c("ego_id","alt_id")]],"initial_wealth"]))
              node_r0[i,]$initial_rel_rank = rank1(na.omit(node_r0[node_r0$ego_id %in% node_r0[i,colnames(node_r0)[substr(colnames(node_r0),1,6)
              %in% c("ego_id","alt_id")]],"initial_wealth"]))/length(na.omit(node_r0[node_r0$ego_id %in%
              node_r0[i,colnames(node_r0)[substr(colnames(node_r0),1,6) %in% c("ego_id","alt_id")]],"initial_wealth"]))
              }
            #Finalization of round 0 and Visualization
            #plot(graph.data.frame(link_r0[link_r0$connected==1,],directed=F)) #plot.igraph
            node_r0$everIsolated = 0
            node_r0$maxDegreeLost = NA
            result[result$round==0,2:25] = c(length(node_r0$ego_id),length(node_r0[node_r0$group=="rich",]$ego_id),NA,mean(node_r0$initial_degree),mean(node_r0$initial_wealth),gini(node_r0$initial_wealth),gmd(node_r0$initial_wealth),NA,mean(node_r0[node_r0$group=="rich",]$initial_degree),mean(node_r0[node_r0$group=="rich",]$initial_wealth),gini(node_r0[node_r0$group=="rich",]$initial_wealth),gmd(node_r0[node_r0$group=="rich",]$initial_wealth),NA,mean(node_r0[node_r0$group=="poor",]$initial_degree),mean(node_r0[node_r0$group=="poor",]$initial_wealth),gini(node_r0[node_r0$group=="poor",]$initial_wealth),gmd(node_r0[node_r0$group=="poor",]$initial_wealth),
                                             as.numeric(ifelse(is.na(table(node_r0$initial_degree<=isolationDegree)["TRUE"]),0,1)),
                                             as.numeric(sum(node_r0$everIsolated)/length(node_r0$ego_id)),
                                             NA,
                                             NA,
                                             NA,NA,NA
                                             )
            
            g_r0 = graph_from_data_frame(link_r0[link_r0$connected==1,][1:2], directed = FALSE, vertices=node_r0)
            node_r0$prev_eigen = eigen_centrality(g_r0)$vector
            
            #For the loop at the next round (for round 1, the initial one is the same as the previous [1 prior] one)
            node_import = node_r0
            node_import$initial_coop = NA
            node_import$prev_coop = NA
            node_import$prev_wealth = node_import$initial_wealth
            node_import$prev_degree = node_import$initial_degree
            node_import$prev_avg_env_wealth = node_import$initial_avg_env_wealth
            node_import$prev_local_gini = node_import$initial_local_gini
            node_import$prev_rel_rank = node_import$initial_rel_rank
            node_import$prev_local_rate_coop = NA
            link_import = link_r0
            
            
            
            #####################################################
            # Section 3: Rounds 1 to 10 or more (behaviors in simulation: the equation of cooperation is different at round 1 because of no history)
            #3-1: Cooperation phase
            for (k in 1:L)
            {
              node_rX = node_import #Importing data
              node_rX$round = node_rX$round + 1
              node_rX[is.na(node_rX$prev_degree)==1,"prev_degree"] = 0
              node_rX[is.na(node_rX$prev_eigen)==1,"prev_eigen"] = 0
              node_rX[is.na(node_rX$prev_local_rate_coop)==1,"prev_local_rate_coop"] = 0
              #Only this calculation needs to change from Round 1
              if(modelForPrediction=="linear"){
                if (k==1) {
                  node_rX$prob_coop = as.numeric(V==0)*inv.logit((-1.816665) + (2.086067)*coop_rp1 + (1.800153)*coop_rp2) + as.numeric(V==1)*inv.logit((-2.031577) + (2.427157)*coop_rp1 + (1.684193)*coop_rp2 + (-1.528851)*GINI)
                  } else {
                  node_rX$prob_coop = as.numeric(V==0 & node_rX$prev_coop==0)*inv.logit(-1.039916) + as.numeric(V==0 & node_rX$prev_coop==1)*inv.logit(2.062023) + as.numeric(V==1 & node_rX$prev_coop==0)*inv.logit((-0.2574838)*as.numeric(node_rX$prev_avg_env_wealth - node_rX$prev_wealth > 0) + (-1.214198)*GINI + (2.508148)*GINI*as.numeric(node_rX$prev_avg_env_wealth - node_rX$prev_wealth > 0) + (-0.9749075)) + as.numeric(V==1 & node_rX$prev_coop==1)*inv.logit((- 0.6197254)*as.numeric(node_rX$prev_avg_env_wealth - node_rX$prev_wealth > 0) + (-0.7480261)*GINI + (1.169674)*GINI*as.numeric(node_rX$prev_avg_env_wealth - node_rX$prev_wealth > 0) + (1.356784))
                  } 
              }
              if(modelForPrediction=="random forest"){
                if (k==1) {
                    if(V==1){node_rX$prob_coop = predict(model1,
                                                         newdata=
                                                           data.frame(
                                                             behavior.p1 = coop_rp1,
                                                             behavior.p2 = coop_rp2,
                                                             gini = GINI
                                                           ),
                                                         type = "prob"
                                                         )[[1]]$C}
                    else if(V==0){node_rX$prob_coop = predict(model1,
                                                         newdata=
                                                           data.frame(
                                                             behavior.p1 = coop_rp1,
                                                             behavior.p2 = coop_rp2
                                                           ),
                                                         type = "prob"
                                                         )[[1]]$C}
                  } else {
                    if(V==1){node_rX$prob_coop = predict(model2,
                                                         newdata=
                                                           data.frame(
                                                             prevCoop = node_rX$prev_coop,
                                                             gini = GINI,
                                                             alterPrevWealth = node_rX$prev_avg_env_wealth,
                                                             egoPrevWealth = node_rX$prev_wealth
                                                           ),
                                                         type = "prob"
                                                         )[[1]]$C}
                    else if(V==0){node_rX$prob_coop = predict(model2,
                                                         newdata=
                                                           data.frame(
                                                             prevCoop = node_rX$prev_coop,
                                                             alterPrevWealth = node_rX$prev_avg_env_wealth,
                                                             egoPrevWealth = node_rX$prev_wealth
                                                           ),
                                                         type = "prob"
                                                         )[[1]]$C}
                  }
              }
              #####rearrange node degrees before round 1 depending on cooperation in practice rounds!
              if(k==1){
                if(fractionCoop==0){
                  node_rX$prob_coop
                  node_rX$coop = apply(data.frame(node_rX$prob_coop),1,function(x) {sample(1:0,1,prob=c(x,(1-x)))})
                  coop_rp_init = coop_rp
                  }
                if(fractionCoop>0){
                  prob_coop_df = NULL
                  nodesCoop = NULL
                  #nodesCoop = node_rX$prev_degree<=quantile(node_rX$prev_degree,fractionCoop) #assign low-eigenvector centrality nodes to cooperators
                  #assign defectors to designated nodes
                  
                  if(fractionCoop<1){nodesCoop = node_rX$prev_eigen<quantile(node_rX$prev_eigen,fractionCoop) & node_rX$prev_eigen>=quantile(node_rX$prev_eigen,fractionCoop-0.25)}
                  else if(fractionCoop==1){nodesCoop = node_rX$prev_eigen<=quantile(node_rX$prev_eigen,fractionCoop) & node_rX$prev_eigen>=quantile(node_rX$prev_eigen,fractionCoop-0.25)}
                  prob_coop_df = 
                    data.frame(
                      prob_coop = rev(node_rX$prob_coop[order(coop_rp)]),
                      node_number = c(which(!nodesCoop),which(nodesCoop))
                    )
                  node_rX$prob_coop = prob_coop_df[order(prob_coop_df$node_number),]$prob_coop
                  #coop_rp of the rearranged nodes
                  coop_rp_init = rev(coop_rp[order(coop_rp)])[order(prob_coop_df$node_number)]
                  node_rX$coop = apply(data.frame(node_rX$prob_coop),1,function(x) {sample(1:0,1,prob=c(x,(1-x)))})
                }
              } else {
                node_rX$coop = apply(data.frame(node_rX$prob_coop),1,function(x) {sample(1:0,1,prob=c(x,(1-x)))})
              }
              if (k==1) {
                node_rX$initial_coop = node_rX$coop
                } else {
                node_rX$initial_coop = node_rX$initial_coop
                }
              node_rX$cost = (-50)*node_rX$coop*node_rX$prev_degree
              node_rX$n_coop_received = NA
              for (i in 1:(dim(node_rX)[1]))
                {
                node_rX[i,]$n_coop_received = sum(node_rX[node_rX$ego_id %in% node_rX[i,colnames(node_rX)[substr(colnames(node_rX),1,6) ==
                "alt_id"]],"coop"])
                }
              node_rX$benefit = 100*node_rX$n_coop_received
              node_rX$payoff = node_rX$cost + node_rX$benefit
              node_rX$wealth = node_rX$prev_wealth + node_rX$payoff
              node_rX$rel_rank = NA
              node_rX$local_rate_coop = NA
              for (i in 1:dim(node_rX)[1])
                {
                node_rX[i,]$rel_rank = rank1(na.omit(node_rX[node_rX$ego_id %in% node_rX[i,colnames(node_rX)[substr(colnames(node_rX),1,6) %in%
                c("ego_id","alt_id")]],"wealth"]))/length(na.omit(node_rX[node_rX$ego_id %in%
                node_rX[i,colnames(node_rX)[substr(colnames(node_rX),1,6) %in% c("ego_id","alt_id")]],"wealth"]))
                node_rX[i,]$local_rate_coop = mean(na.omit(node_rX[node_rX$ego_id %in% node_rX[i,colnames(node_rX)[substr(colnames(node_rX),1,6) %in%
                c("ego_id","alt_id")]],"coop"]))
                }
              node_rX$growth = as.numeric((node_rX$wealth/node_rX$prev_wealth) > 1)
              node_rX = node_rX[,c("ego_id","round","group","prev_degree","initial_wealth","initial_local_gini","initial_coop","coop","wealth","rel_rank","local_rate_coop","growth","everIsolated","maxDegreeLost")] #Pruning the previous-round data (degree is not updating yet)
              
              #3-2: Rewiring phase
              # 30% of ties (unidirectional) are being rewired
              link_rX_1 = link_import #Importing data (bidirectioanl ego-alter [ego_id < alter_id])
              colnames(link_rX_1) = c("ego_id","alt_id","prev_connected")
              link_rX_1$challenge = sample(0:1,dim(link_rX_1)[1],replace=TRUE,prob=c(0.7,0.3)) # The bidirectional ties being rewired are selected (rewiring rate = 0.3).
              ego_node_data =
              node_rX[,c("ego_id","wealth","coop","prev_degree","initial_wealth","initial_local_gini","initial_coop","rel_rank","local_rate_coop","growth")]
              colnames(ego_node_data) =
              c("ego_id","ego_wealth","ego_coop","ego_prev_degree","ego_initial_wealth","ego_initial_local_gini","ego_initial_coop","ego_rel_rank","ego_local_rate_coop","ego_growth")
              alt_node_data =
              node_rX[,c("ego_id","wealth","coop","prev_degree","initial_wealth","initial_local_gini","initial_coop","rel_rank","local_rate_coop","growth")]
              colnames(alt_node_data) =
              c("alt_id","alt_wealth","alt_coop","alt_prev_degree","alt_initial_wealth","alt_initial_local_gini","alt_initial_coop","alt_rel_rank","alt_local_rate_coop","alt_growth")
              link_rX_2 = merge(x=link_rX_1,y=ego_node_data,all.x=TRUE,all.y=FALSE,by="ego_id")
              link_rX_3 = merge(x=link_rX_2,y=alt_node_data,all.x=TRUE,all.y=FALSE,by="alt_id")
              link_rX_3$choice = sample(c("ego","alt"),dim(link_rX_3)[1],replace=TRUE,prob=c(0.5,0.5)) #decision maker for breaking a link, which is a unilateral decision
              #ego_prob: probability of choosing to connect when challenged (asked)
              
              if(modelForPrediction=="linear"){
                link_rX_3$ego_prob = inv.logit((0.5134401)*link_rX_3$prev_connected + (-0.852406)*link_rX_3$ego_coop + (2.96549)*link_rX_3$alt_coop + (-0.1808545))
                link_rX_3$alt_prob = inv.logit((0.5134401)*link_rX_3$prev_connected + (-0.852406)*link_rX_3$alt_coop + (2.96549)*link_rX_3$ego_coop + (-0.1808545))}
              if(modelForPrediction=="random forest"){
                link_rX_3$ego_prob = predict(model3,
                                             newdata=
                                               data.frame(
                                                 previouslyconnected = link_rX_3$prev_connected,
                                                 ego_behavior = link_rX_3$ego_coop,
                                                 alter_behavior = link_rX_3$alt_coop
                                                 ),
                                            type = "prob"
                                             )[[1]]$C
                link_rX_3$alt_prob = predict(model3,
                                             newdata=
                                               data.frame(
                                                 previouslyconnected = link_rX_3$prev_connected,
                                                 ego_behavior = link_rX_3$alt_coop,
                                                 alter_behavior = link_rX_3$ego_coop
                                                 ),
                                            type = "prob"
                                             )[[1]]$C
              }
              link_rX_3$prob_connect = ifelse(link_rX_3$prev_connected == 1, ifelse(link_rX_3$choice == "ego", link_rX_3$ego_prob,
              link_rX_3$alt_prob), link_rX_3$ego_prob*link_rX_3$alt_prob)
              link_rX_3$connect_update = apply(data.frame(link_rX_3$prob_connect),1, function(x) {sample(1:0,1,prob=c(x,(1-x)))})
              link_rX_3$connected = ifelse(link_rX_3$challenge==0,link_rX_3$prev_connected,link_rX_3$connect_update)
              link_rX = link_rX_3[,c("ego_id","alt_id","connected")] #pruning and data is updated
              #Reflect the degree and local gini coefficient into the node data
              link_rXc_ego = link_rX[link_rX$connected==1,]
              link_rXc_alt = link_rX[link_rX$connected==1,]
              colnames(link_rXc_alt) = c("alt_id","ego_id","connected")
              link_rXc = rbind(link_rXc_ego,link_rXc_alt)
              link_rXc = link_rXc[order(link_rXc$ego_id),]
              link_rXc$alternumber = NA
              link_rXc[1,]$alternumber = 1
              for (i in 1:(dim(link_rXc)[1]-1))
                {
                  if (link_rXc[i,]$ego_id == link_rXc[i+1,]$ego_id)
                  {
                  link_rXc[i+1,]$alternumber = link_rXc[i,]$alternumber + 1
                  }
                  else
                  {
                  link_rXc[i+1,]$alternumber = 1
                  }
                  #print(i)
                }
              link_rXc2 = reshape(link_rXc, direction = "wide", idvar=c("ego_id","connected"), timevar="alternumber")
              link_rXc2$degree = apply(link_rXc2[,colnames(link_rXc2)[substr(colnames(link_rXc2),1,3) == "alt"]],1,function(x) {length(na.omit(x))})
              node_rX_final = merge(x=node_rX[,c("ego_id","round","group","initial_wealth","initial_local_gini","initial_coop","coop","wealth","growth","everIsolated","maxDegreeLost")],y=link_rXc2,all.x=TRUE,all.y=FALSE,by="ego_id")
              node_rX_final[is.na(node_rX_final$degree)==1,"degree"] = 0
              node_rX_final$avg_env_wealth = NA
              node_rX_final$local_gini = NA #needs to be updated because the social network changes at the rewiring phase
              node_rX_final$local_rate_coop = NA
              node_rX_final$rel_rank = NA
              for (i in 1:dim(node_rX_final)[1])
                {
                node_rX_final[i,]$avg_env_wealth = mean(na.omit(node_rX_final[node_rX_final$ego_id %in%
                node_rX_final[i,colnames(node_rX_final)[substr(colnames(node_rX_final),1,6) %in% c("ego_id","alt_id")]],"wealth"]))
                node_rX_final[i,]$local_gini = gini(na.omit(node_rX_final[node_rX_final$ego_id %in%
                node_rX_final[i,colnames(node_rX_final)[substr(colnames(node_rX_final),1,6) %in% c("ego_id","alt_id")]],"wealth"]))
                node_rX_final[i,]$local_rate_coop = mean(na.omit(node_rX_final[node_rX_final$ego_id %in%
                node_rX_final[i,colnames(node_rX_final)[substr(colnames(node_rX_final),1,6) %in% c("ego_id","alt_id")]],"coop"]))
                node_rX_final[i,]$rel_rank = rank1(na.omit(node_rX_final[node_rX_final$ego_id %in%
                node_rX_final[i,colnames(node_rX_final)[substr(colnames(node_rX_final),1,6) %in%
                c("ego_id","alt_id")]],"wealth"]))/length(na.omit(node_rX_final[node_rX_final$ego_id %in%
                node_rX_final[i,colnames(node_rX_final)[substr(colnames(node_rX_final),1,6) %in% c("ego_id","alt_id")]],"wealth"]))
                node_rX_final[i,]$everIsolated = ifelse(node_rX_final[i,]$everIsolated==1,1,ifelse(node_rX_final[i,]$degree<=isolationDegree,1,0))
                node_rX_final[i,]$maxDegreeLost = pmax(node_r0[i,]$initial_degree - node_rX_final[i,]$degree, node_rX_final[i,]$maxDegreeLost, na.rm=TRUE)
              }
              
              
              #Finalization of round X and Visualization
              #plot(graph.data.frame(link_rX[link_rX$connected==1,],directed=F)) #plot.igraph
              result[result$round==k,2:25] =
              c(length(node_rX_final$ego_id),length(node_rX_final[node_rX_final$group=="rich",]$ego_id),mean(node_rX_final$coop),mean(node_rX_final$degree),mean(node_rX_final$wealth),gini(node_rX_final$wealth),gmd(node_rX_final$wealth),mean(node_rX_final[node_rX_final$group=="rich",]$coop),mean(node_rX_final[node_rX_final$group=="rich",]$degree),mean(node_rX_final[node_rX_final$group=="rich",]$wealth),gini(node_rX_final[node_rX_final$group=="rich",]$wealth),gmd(node_rX_final[node_rX_final$group=="rich",]$wealth),mean(node_rX_final[node_rX_final$group=="poor",]$coop),mean(node_rX_final[node_rX_final$group=="poor",]$degree),mean(node_rX_final[node_rX_final$group=="poor",]$wealth),gini(node_rX_final[node_rX_final$group=="poor",]$wealth),gmd(node_rX_final[node_rX_final$group=="poor",]$wealth),
                                             as.numeric(ifelse(is.na(table(node_rX_final$degree<=isolationDegree)["TRUE"]),0,1)),
                                             as.numeric(sum(node_rX_final$everIsolated)/length(node_rX_final$ego_id)),
                prop.table(table(node_rX_final[node_rX_final$initial_coop==1]$coop))["0"],
                prop.table(table(node_rX_final[node_rX_final$initial_coop==0]$coop))["1"],
                suppressWarnings({mean(node_rX_final$maxDegreeLost,na.rm=TRUE)}),
                suppressWarnings({mean(node_rX_final[node_rX_final$initial_coop==1]$maxDegreeLost,na.rm=TRUE)}),
                suppressWarnings({mean(node_rX_final[node_rX_final$initial_coop==0]$maxDegreeLost,na.rm=TRUE)})
                )
              
              #For the loop
              node_import = node_rX_final
              colnames(node_import)[colnames(node_import) %in%
              c("coop","wealth","growth","degree","avg_env_wealth","local_gini","local_rate_coop","rel_rank")] =
              c("prev_coop","prev_wealth","prev_growth","prev_degree","prev_avg_env_wealth","prev_local_gini","prev_local_rate_coop","prev_rel_rank")
              link_import = link_rX
              #print(paste0("Round ",k," is done."))
              g_rX = graph_from_data_frame(link_rX[link_rX$connected==1,][1:2], directed = FALSE, vertices=node_rX_final)
              node_import$prev_eigen = eigen_centrality(g_rX)$vector
            
            }
            
           
            trends.df = rbind(trends.df,cbind(result[c("round","gini","gmd","avg_wealth","avg_coop","avg_degree")],V,GINI,fractionCoop))
            
            link_rX_final = data.table::melt(setDT(node_rX_final),
                                     measure = patterns('alt_id'),
                                     variable.name = 'linkNumber', 
                                     value.name = c('alt_id'))
            link_rX_final = data.frame(link_rX_final)[c("ego_id","alt_id")]
            link_rX_final = link_rX_final[complete.cases(link_rX_final),]
            link_rX_final = data.frame(t(unique(apply(link_rX_final, 1, function(x) sort(x))))) %>% distinct(X1, X2)
            node_g_final = data.frame(node_rX_final)[c("ego_id","initial_coop","coop")]
            node_g_final$initial_coop = factor(node_g_final$initial_coop)
            
            g_rX_final = graph_from_data_frame(link_rX_final, directed = FALSE, vertices=node_g_final)
            g_r0 = graph_from_data_frame(link_r0[link_r0$connected==1,][1:2], directed = FALSE, vertices=node_r0)
            
            E(g_r0)$coopEdgeC = sapply(E(g_r0), function(e) prod(ifelse(V(g_r0)[inc(e)]$coop_rp=="C",1,0)))
            E(g_r0)$coopEdgeD = sapply(E(g_r0), function(e) prod(ifelse(V(g_r0)[inc(e)]$coop_rp=="D",1,0)))
            E(g_r0)$coopEdgeCD = sapply(E(g_r0), function(e) ifelse(sum(ifelse(V(g_r0)[inc(e)]$coop_rp=="C",1,0))==1,1,0))
            
            #C-assortativity, defined as number of observed C-C edges out of total possible C-C edges
            homophilyC[m] = sum(E(g_r0)$coopEdgeC) / (table(V(g_r0)$coop_rp)["C"]*(table(V(g_r0)$coop_rp)["C"]-1)/2)
            #D-assortativity, defined as number of observed C-C edges out of total possible C-C edges
            homophilyD[m] = sum(E(g_r0)$coopEdgeD) / (table(V(g_r0)$coop_rp)["D"]*(table(V(g_r0)$coop_rp)["D"]-1)/2)
            #heterophily, defined as number of observed C-D edges out of total possible C-D edges
            heterophily[m] = sum(E(g_r0)$coopEdgeCD) / (table(V(g_r0)$coop_rp)["C"]*table(V(g_r0)$coop_rp)["D"])
            
            coopFrac[m] = fractionCoop
            avgCoop[m] = prop.table(table(V(g_r0)$coop_rp))["C"]
            avgCoopFinal[m] = result[result$round==10,]$avg_coop
            percentIsolation[m] = max(result[result$round>=1,]$percentIsolation)
            isolation[m] = max(result[result$round>=1,]$isolation)
            #percentage of isolation among those who cooperated in both practice rounds
            percentIsolationC[m] = sum(node_rX_final[coop_rp_init==1,]$everIsolated)/length(node_rX_final[coop_rp_init==1,]$everIsolated)
            #percentage of isolation among those who defected at least once in practice rounds
            percentIsolationD[m] = sum(node_rX_final[coop_rp_init<=0.5,]$everIsolated)/length(node_rX_final[coop_rp_init<=0.5,]$everIsolated)
            
            nCommunities[m] = max(membership(cluster_louvain(g_rX_final)),na.rm=TRUE)
            communitySize[m] = mean(table(membership(cluster_louvain(g_rX_final))),na.rm=TRUE)
            assortativityInitial[m] = assortativity(g_r0, V(g_r0)$coop_rp == "C")
            assortativityFinal[m] = assortativity(g_rX_final, V(g_r0)$coop_rp == "C")
            conversionRate[m] = prop.table(table(V(g_rX_final)$coop == ifelse(V(g_r0)$coop_rp=="C","1","0")))["FALSE"]
            conversionToD[m] = prop.table(table(V(g_rX_final)$coop[V(g_r0)$coop_rp == "C"]))["0"]
            conversionToC[m] = prop.table(table(V(g_rX_final)$coop[V(g_r0)$coop_rp == "C"]))["1"]
            transitivity[m] = mean(transitivity(g_rX_final, type="global"),na.rm=TRUE)
            degree[m] = mean(igraph::degree(g_rX_final),na.rm=TRUE)
            degreeC[m] = mean(igraph::degree(g_r0)[coop_rp_init==1],na.rm=TRUE)
            degreeD[m] = mean(igraph::degree(g_r0)[coop_rp_init<=0.5],na.rm=TRUE)
            meanConversionToD[m] = mean(result[result$round>=2,]$meanConversionToD, na.rm=TRUE)
            meanConversionToC[m] = mean(result[result$round>=2,]$meanConversionToC, na.rm=TRUE)
            degreeLost[m] = result[result$round==10,]$degreeLost
            degreeLostC[m] = result[result$round==10,]$degreeLostC
            degreeLostD[m] = result[result$round==10,]$degreeLostD
            avg_wealth[m] = result[result$round==10,]$avg_wealth
            gini[m] = result[result$round==10,]$gini
        
          }
          
        df.netIntLowDegree = rbind(df.netIntLowDegree,
                          data.frame(
                            coopFrac = coopFrac,
                            avgCoop = avgCoop,
                            avgCoopFinal = avgCoopFinal,
                            percentIsolation = percentIsolation,
                            isolation = isolation,
                            percentIsolationC = percentIsolationC,
                            percentIsolationD = percentIsolationD,
                            nCommunities = nCommunities,
                            communitySize = communitySize,
                            assortativityInitial = assortativityInitial,
                            assortativityFinal = assortativityFinal,
                            conversionRate = conversionRate,
                            conversionToD = conversionToD, 
                            conversionToC = conversionToC, 
                            homophilyC = homophilyC,
                            homophilyD = homophilyD,
                            heterophily = heterophily,
                            transitivity = transitivity, 
                            degree = degree, 
                            degreeC = degreeC, 
                            degreeD = degreeD,
                            meanConversionToD = meanConversionToD, 
                            meanConversionToC = meanConversionToC,
                            degreeLost = degreeLost,
                            degreeLostC = degreeLostC,
                            degreeLostD = degreeLostD,
                            avg_wealth = avg_wealth,
                            gini = gini
                            ))
        #plot(g_r0,vertex.color=V(g_rX_final)$initial_coop,vertex.label=ifelse(is.na(V(g_rX_final)$initial_coop),"NA",ifelse(V(g_rX_final)$initial_coop==1,"C","D")),main=paste("fracCoop=",frac,", round 0",sep=""))
        #plot(g_rX_final,vertex.color=V(g_rX_final)$initial_coop,vertex.label=ifelse(is.na(V(g_rX_final)$initial_coop),"NA",ifelse(V(g_rX_final)$initial_coop==1,"C","D")),main=paste("fracCoop=",frac,", final round",sep=""))
        
      }
      
    sum.netIntLowDegree <- data.frame(
      df.netIntLowDegree %>% 
        group_by(coopFrac) %>%
          summarise(
            mean.isolation = mean(isolation),
            ci.isolation   = 1.96 * sd(isolation)/sqrt(n()),
            mean.percentIsolation = mean(percentIsolation),
            ci.percentIsolation   = 1.96 * sd(percentIsolation)/sqrt(n()),
            mean.percentIsolationC = mean(percentIsolationC,na.rm=TRUE),
            ci.percentIsolationC   = 1.96 * sd(percentIsolationC,na.rm=TRUE)/sqrt(sum(isolation)),
            mean.percentIsolationD = mean(percentIsolationD,na.rm=TRUE),
            ci.percentIsolationD   = 1.96 * sd(percentIsolationD,na.rm=TRUE)/sqrt(sum(isolation)),
            mean.avgCoop = mean(avgCoop,na.rm=TRUE),
            ci.avgCoop   = 1.96 * sd(avgCoop,na.rm=TRUE)/sqrt(n()),
            mean.avgCoopFinal = mean(avgCoopFinal,na.rm=TRUE),
            ci.avgCoopFinal   = 1.96 * sd(avgCoopFinal,na.rm=TRUE)/sqrt(n()),
            mean.nCommunities = mean(nCommunities,na.rm=TRUE),
            ci.nCommunities   = 1.96 * sd(nCommunities,na.rm=TRUE)/sqrt(n()),
            mean.communitySize = mean(communitySize,na.rm=TRUE),
            ci.communitySize   = 1.96 * sd(communitySize,na.rm=TRUE)/sqrt(n()),
            mean.assortativityInitial = mean(assortativityInitial,na.rm=TRUE),
            ci.assortativityInitial   = 1.96 * sd(assortativityInitial,na.rm=TRUE)/sqrt(n()),
            mean.assortativityFinal = mean(assortativityFinal,na.rm=TRUE),
            ci.assortativityFinal   = 1.96 * sd(assortativityFinal,na.rm=TRUE)/sqrt(n()),
            mean.conversionRate = mean(conversionRate,na.rm=TRUE),
            ci.conversionRate   = 1.96 * sd(conversionRate,na.rm=TRUE)/sqrt(n()),
            mean.conversionToD = mean(conversionToD,na.rm=TRUE),
            ci.conversionToD   = 1.96 * sd(conversionToD,na.rm=TRUE)/sqrt(n()),
            mean.conversionToC = mean(conversionToC,na.rm=TRUE),
            ci.conversionToC   = 1.96 * sd(conversionToC,na.rm=TRUE)/sqrt(n()),
            mean.homophilyC = mean(homophilyC,na.rm=TRUE),
            ci.homophilyC   = 1.96 * sd(homophilyC,na.rm=TRUE)/sqrt(n()),
            mean.homophilyD = mean(homophilyD,na.rm=TRUE),
            ci.homophilyD   = 1.96 * sd(homophilyD,na.rm=TRUE)/sqrt(n()),
            mean.heterophily = mean(heterophily,na.rm=TRUE),
            ci.heterophily   = 1.96 * sd(heterophily,na.rm=TRUE)/sqrt(n()),
            mean.transitivity = mean(transitivity,na.rm=TRUE),
            ci.transitivity   = 1.96 * sd(transitivity,na.rm=TRUE)/sqrt(n()),
            mean.degree = mean(degree,na.rm=TRUE),
            ci.degree   = 1.96 * sd(degree,na.rm=TRUE)/sqrt(n()),
            mean.degreeC = mean(degreeC,na.rm=TRUE),
            ci.degreeC   = 1.96 * sd(degreeC,na.rm=TRUE)/sqrt(n()),
            mean.degreeD = mean(degreeD,na.rm=TRUE),
            ci.degreeD   = 1.96 * sd(degreeD,na.rm=TRUE)/sqrt(n()),
            mean.meanConversionToD = mean(meanConversionToD,na.rm=TRUE),
            ci.meanConversionToD   = 1.96 * sd(meanConversionToD,na.rm=TRUE)/sqrt(n()),
            mean.meanConversionToC = mean(meanConversionToC,na.rm=TRUE),
            ci.meanConversionToC   = 1.96 * sd(meanConversionToC,na.rm=TRUE)/sqrt(n()),
            mean.degreeLost = mean(degreeLost,na.rm=TRUE),
            ci.degreeLost   = 1.96 * sd(degreeLost,na.rm=TRUE)/sqrt(n()),
            mean.degreeLostC = mean(degreeLostC,na.rm=TRUE),
            ci.degreeLostC   = 1.96 * sd(degreeLostC,na.rm=TRUE)/sqrt(n()),
            mean.degreeLostD = mean(degreeLostD,na.rm=TRUE),
            ci.degreeLostD   = 1.96 * sd(degreeLostD,na.rm=TRUE)/sqrt(n()),
            mean.avg_wealth = mean(avg_wealth,na.rm=TRUE),
            ci.avg_wealth   = 1.96 * sd(avg_wealth,na.rm=TRUE)/sqrt(n()),
            mean.gini = mean(gini,na.rm=TRUE),
            ci.gini   = 1.96 * sd(gini,na.rm=TRUE)/sqrt(n())
            )
      )
          
    kable(sum.netIntLowDegree[c(1:9)]) %>% kableExtra::kable_styling(font_size = 10)
    kable(sum.netIntLowDegree[c(1,10:17)]) %>% kableExtra::kable_styling(font_size = 10) 
    kable(sum.netIntLowDegree[c(1,18:25)]) %>% kableExtra::kable_styling(font_size = 10) 
    kable(sum.netIntLowDegree[c(1,26:33)]) %>% kableExtra::kable_styling(font_size = 10) 
    kable(sum.netIntLowDegree[c(1,34:ncol(sum.netIntLowDegree))]) %>% kableExtra::kable_styling(font_size = 10) 
    
    compare_means(percentIsolation ~ coopFrac, data=df.netIntLowDegree)
    compare_means(avgCoop ~ coopFrac, data=df.netIntLowDegree)
    compare_means(avgCoopFinal ~ coopFrac, data=df.netIntLowDegree)
    compare_means(nCommunities ~ coopFrac, data=df.netIntLowDegree)
    compare_means(communitySize ~ coopFrac, data=df.netIntLowDegree)
    compare_means(assortativityInitial ~ coopFrac, data=df.netIntLowDegree)
    compare_means(assortativityFinal ~ coopFrac, data=df.netIntLowDegree)
    #compare_means(conversionRate ~ coopFrac, data=df.netIntLowDegree)
    #compare_means(conversionToD ~ coopFrac, data=df.netIntLowDegree)
    #compare_means(conversionToC ~ coopFrac, data=df.netIntLowDegree)
    #compare_means(degreeC ~ coopFrac, data=df.netIntLowDegree)
    #compare_means(degreeD ~ coopFrac, data=df.netIntLowDegree)
    #compare_means(meanConversionToD ~ coopFrac, data=df.netIntLowDegree)
    #compare_means(meanConversionToC ~ coopFrac, data=df.netIntLowDegree)
    #compare_means(degreeLost ~ coopFrac, data=df.netIntLowDegree)
    #compare_means(degreeLostC ~ coopFrac, data=df.netIntLowDegree)
    #compare_means(degreeLostD ~ coopFrac, data=df.netIntLowDegree)
    
    summary(lm(percentIsolation ~ assortativityInitial, data=df.netIntLowDegree))
    
    #plot(df.netIntLowDegree$assortativityInitial, df.netIntLowDegree$percentIsolation)
    
    
    
    #percentIsolation
    g.percentIsolation = ggbarplot(data=df.netIntLowDegree, x="coopFrac", y="percentIsolation", add = "mean_se", color="coopFrac") +
      stat_compare_means(ref.group = "0", label = "p.signif", label.y = 0.098, method="t.test", color="black") +  
      labs(
        title = paste("Isolation when defectors are assigned to 25% of nodes by degree, ","V=",V,", Gini=",GINI,sep=""),
        x = "Eigenvector centrality percentile of nodes assigned to defectors ",
        y = "Propoption of ever-isolated individuals") +
      annotate("text", x=1, y=0.0990, label= "ref", color="black") +
      annotate("text", x=2.4, y= -0.0022, label= "Lowest degree nodes assigned to defectors", size=2.5) +
      geom_segment(aes(x = 3.3, y = -0.0024, xend = 3.7, yend = -0.0024), linewidth=0.2, arrow = arrow(length = unit(0.1, "cm"))) +
      annotate("text", x=4.6, y= -0.0022, label= "Highest degree nodes assigned to defectors", size=2.5) +
      theme_bw() +
      theme(plot.title = element_text(hjust = 0.5, size=12),legend.position="none") +
      coord_cartesian(ylim=c(0,0.10)) + 
      scale_x_discrete(labels=c('Control','0-25','25-50','50-75','75-100')) +
      scale_color_manual(values = c('0' = "black",'0.25'="black",'0.5'="black",'0.75'="black",'1'="black")) +
      geom_vline(xintercept = 1.5, linetype = "longdash")
    print(g.percentIsolation)
    
    #percentIsolationC
    #percentage of isolation among those who cooperated in both practice rounds
    g.percentIsolationC = ggbarplot(data=df.netIntLowDegree, x="coopFrac", y="percentIsolationC", add = "mean_se") +
      stat_compare_means(ref.group = "0", label = "p.signif", label.y = 0.098, method="t.test", color="black") +  
      labs(
        title = paste("Isolation among initial cooperators, ","V=",V,", Gini=",GINI,sep=""),
        x = "Eigenvector centrality percentile of nodes assigned to defectors ",
        y = "Propoption of ever-isolated individuals") +
      annotate("text", x=1, y=0.0990, label= "ref", color="black") +
      annotate("text", x=2.4, y= -0.0022, label= "Lowest degree nodes assigned to defectors", size=2.5) +
      geom_segment(aes(x = 3.3, y = -0.0024, xend = 3.7, yend = -0.0024), linewidth=0.2, arrow = arrow(length = unit(0.1, "cm"))) +
      annotate("text", x=4.6, y= -0.0022, label= "Highest degree nodes assigned to defectors", size=2.5) +
      theme_bw() +
      theme(plot.title = element_text(hjust = 0.5, size=12),legend.position="none") +
      coord_cartesian(ylim=c(0,0.10)) + 
      scale_x_discrete(labels=c('Control','0-25','25-50','50-75','75-100')) +
      scale_color_manual(values = c('0' = "black",'0.25'="black",'0.5'="black",'0.75'="black",'1'="black")) +
      geom_vline(xintercept = 1.5, linetype = "longdash")
    print(g.percentIsolationC)
    
    #percentIsolationD
    #percentage of isolation among those who defected at least once in practice rounds
    g.percentIsolationD = ggbarplot(data=df.netIntLowDegree, x="coopFrac", y="percentIsolationD", add = "mean_se") +
      stat_compare_means(ref.group = "0", label = "p.signif", label.y = 0.298, method="t.test", color="black") +  
      labs(
        title = paste("Isolation among initial defectors, ","V=",V,", Gini=",GINI,sep=""),
        x = "Eigenvector centrality percentile of nodes assigned to defectors ",
        y = "Propoption of ever-isolated individuals") +
      annotate("text", x=1, y=0.2990, label= "ref", color="black") +
      annotate("text", x=2.4, y= -0.0062, label= "Lowest degree nodes assigned to defectors", size=2.5) +
      geom_segment(aes(x = 3.3, y = -0.0064, xend = 3.7, yend = -0.0064), linewidth=0.2, arrow = arrow(length = unit(0.1, "cm"))) +
      annotate("text", x=4.6, y= -0.0062, label= "Highest degree nodes assigned to defectors", size=2.5) +
      theme_bw() +
      theme(plot.title = element_text(hjust = 0.5, size=12),legend.position="none") +
      coord_cartesian(ylim=c(0,0.30)) + 
      scale_x_discrete(labels=c('Control','0-25','25-50','50-75','75-100')) +
      scale_color_manual(values = c('0' = "black",'0.25'="black",'0.5'="black",'0.75'="black",'1'="black")) +
      geom_vline(xintercept = 1.5, linetype = "longdash")
    print(g.percentIsolationD)
      
    #avgCoopFinal
    g.avgCoopFinal = ggbarplot(data=df.netIntLowDegree, x="coopFrac", y="avgCoopFinal", add = "mean_se") +
      stat_compare_means(ref.group = "0", label = "p.signif", label.y = 0.98, method="t.test", color="black") +  
      labs(
        title = paste("Cooperation in final round, ","V=",V,", Gini=",GINI,sep=""),
        x = "Eigenvector centrality percentile of nodes assigned to defectors ",
        y = "Propoption of cooperators in final round") +
      annotate("text", x=1, y=0.990, label= "ref", color="black") +
      annotate("text", x=2.4, y= -0.0212, label= "Lowest degree nodes assigned to defectors", size=2.5) +
      geom_segment(aes(x = 3.3, y = -0.0214, xend = 3.7, yend = -0.0214), linewidth=0.2, arrow = arrow(length = unit(0.1, "cm"))) +
      annotate("text", x=4.6, y= -0.0212, label= "Highest degree nodes assigned to defectors", size=2.5) +
      theme_bw() +
      theme(plot.title = element_text(hjust = 0.5, size=12),legend.position="none") +
      coord_cartesian(ylim=c(0,1.0)) + 
      scale_x_discrete(labels=c('Control','0-25','25-50','50-75','75-100')) +
      scale_color_manual(values = c('0' = "black",'0.25'="black",'0.5'="black",'0.75'="black",'1'="black")) +
      geom_vline(xintercept = 1.5, linetype = "longdash")
    print(g.avgCoopFinal)
    
    #avg_wealth
    g.avg_wealth = ggbarplot(data=df.netIntLowDegree, x="coopFrac", y="avg_wealth", add = "mean_se") +
      stat_compare_means(ref.group = "0", label = "p.signif", label.y = 6800, method="t.test", color="black") +  
      labs(
        title = paste("Wealth in final round, ","V=",V,", Gini=",GINI,sep=""),
        x = "Eigenvector centrality percentile of nodes assigned to defectors ",
        y = "Average wealth in final round") +
      annotate("text", x=1, y=6900, label= "ref", color="black") +
      annotate("text", x=2.4, y= -162, label= "Lowest degree nodes assigned to defectors", size=2.5) +
      geom_segment(aes(x = 3.3, y = -164, xend = 3.7, yend = -164), linewidth=0.2, arrow = arrow(length = unit(0.1, "cm"))) +
      annotate("text", x=4.6, y= -162, label= "Highest degree nodes assigned to defectors", size=2.5) +
      theme_bw() +
      theme(plot.title = element_text(hjust = 0.5, size=12),legend.position="none") +
      coord_cartesian(ylim=c(0,7000)) + 
      scale_x_discrete(labels=c('Control','0-25','25-50','50-75','75-100')) +
      scale_color_manual(values = c('0' = "black",'0.25'="black",'0.5'="black",'0.75'="black",'1'="black")) +
      geom_vline(xintercept = 1.5, linetype = "longdash")
    print(g.avg_wealth)
    
    #gini
    g.gini = ggbarplot(data=df.netIntLowDegree, x="coopFrac", y="gini", add = "mean_se") +
      stat_compare_means(ref.group = "0", label = "p.signif", label.y = 0.48, method="t.test", color="black") +  
      labs(
        title = paste("Gini coefficient in final round, ","V=",V,", Gini=",GINI,sep=""),
        x = "Eigenvector centrality percentile of nodes assigned to defectors ",
        y = "Gini coefficient in final round") +
      annotate("text", x=1, y=0.490, label= "ref", color="black") +
      annotate("text", x=2.4, y= -0.0112, label= "Lowest degree nodes assigned to defectors", size=2.5) +
      geom_segment(aes(x = 3.3, y = -0.0114, xend = 3.7, yend = -0.0114), linewidth=0.2, arrow = arrow(length = unit(0.1, "cm"))) +
      annotate("text", x=4.6, y= -0.0112, label= "Highest degree nodes assigned to defectors", size=2.5) +
      theme_bw() +
      theme(plot.title = element_text(hjust = 0.5, size=12),legend.position="none") +
      coord_cartesian(ylim=c(0,0.50)) + 
      scale_x_discrete(labels=c('Control','0-25','25-50','50-75','75-100')) +
      scale_color_manual(values = c('0' = "black",'0.25'="black",'0.5'="black",'0.75'="black",'1'="black")) +
      geom_vline(xintercept = 1.5, linetype = "longdash")
    print(g.gini)
    
    #degree
    g.degree = ggbarplot(data=df.netIntLowDegree, x="coopFrac", y="degree", add = "mean_se") +
      stat_compare_means(ref.group = "0", label = "p.signif", label.y = 14.8, method="t.test", color="black") +  
      labs(
        title = paste("Degree in final round, ","V=",V,", Gini=",GINI,sep=""),
        x = "Eigenvector centrality percentile of nodes assigned to defectors ",
        y = "Mean degree in final round") +
      annotate("text", x=1, y=14.90, label= "ref", color="black") +
      annotate("text", x=2.4, y= -0.312, label= "Lowest degree nodes assigned to defectors", size=2.5) +
      geom_segment(aes(x = 3.3, y = -0.314, xend = 3.7, yend = -0.314), linewidth=0.2, arrow = arrow(length = unit(0.1, "cm"))) +
      annotate("text", x=4.6, y= -0.312, label= "Highest degree nodes assigned to defectors", size=2.5) +
      theme_bw() +
      theme(plot.title = element_text(hjust = 0.5, size=12),legend.position="none") +
      coord_cartesian(ylim=c(0,15)) + 
      scale_x_discrete(labels=c('Control','0-25','25-50','50-75','75-100')) +
      scale_color_manual(values = c('0' = "black",'0.25'="black",'0.5'="black",'0.75'="black",'1'="black")) +
      geom_vline(xintercept = 1.5, linetype = "longdash")
    print(g.degree)
    
    #transitivity
    g.transitivity = ggbarplot(data=df.netIntLowDegree, x="coopFrac", y="transitivity", add = "mean_se") +
      stat_compare_means(ref.group = "0", label = "p.signif", label.y = 0.98, method="t.test", color="black") +  
      labs(
        title = paste("Transitivity in final round, ","V=",V,", Gini=",GINI,sep=""),
        x = "Eigenvector centrality percentile of nodes assigned to defectors ",
        y = "Transitivity in final round") +
      annotate("text", x=1, y=0.99, label= "ref", color="black") +
      annotate("text", x=2.4, y= -0.0212, label= "Lowest degree nodes assigned to defectors", size=2.5) +
      geom_segment(aes(x = 3.3, y = -0.0214, xend = 3.7, yend = -0.0214), linewidth=0.2, arrow = arrow(length = unit(0.1, "cm"))) +
      annotate("text", x=4.6, y= -0.0212, label= "Highest degree nodes assigned to defectors", size=2.5) +
      theme_bw() +
      theme(plot.title = element_text(hjust = 0.5, size=12),legend.position="none") +
      coord_cartesian(ylim=c(0,1.00)) + 
      scale_x_discrete(labels=c('Control','0-25','25-50','50-75','75-100')) +
      scale_color_manual(values = c('0' = "black",'0.25'="black",'0.5'="black",'0.75'="black",'1'="black")) +
      geom_vline(xintercept = 1.5, linetype = "longdash")
    print(g.transitivity)
    
    #initial C-assortativity     
    plotList <- lapply(
              unique(df.netIntLowDegree$coopFrac),
              function(key) {
                if(key==0){
                  ggplot(data = df.netIntLowDegree[df.netIntLowDegree$coopFrac==key,], aes(x = homophilyC, y = percentIsolation)) + 
                      geom_point() + 
                      scale_x_continuous(paste("C-assortativity, ","Control",sep="")) +
                      scale_y_continuous("Proportion isolated") +
                      geom_smooth(method='lm', formula= y~x) + 
                      stat_cor(method = "pearson")
                }
                else{
                  ggplot(data = df.netIntLowDegree[df.netIntLowDegree$coopFrac==key,], aes(x = homophilyC, y = percentIsolation)) + 
                      geom_point() + 
                      scale_x_continuous(paste("C-assortativity, degree %ile = ",key,sep="")) +
                      scale_y_continuous("Proportion isolated") +
                      geom_smooth(method='lm', formula= y~x) + 
                      stat_cor(method = "pearson")
                }
              }
    )
    plot= ggarrange(plotlist=plotList)
    print(annotate_figure(plot, top = text_grob(paste("Proportion of ever-isolated individuals, ","V=",V,", Gini=", GINI, sep=""), color = "black", face = "bold", size = 10)))
    
    lapply(unique(df.netIntLowDegree$coopFrac),
              function(key) {
                if(key==0){
                  reg = lm(percentIsolation ~ homophilyC + degreeD, data=df.netIntLowDegree[df.netIntLowDegree$coopFrac==key,])
                  print(paste("Regression on proportion of ever-isolated individuals, ","Control"," ; ",sep=""))
                  print(summary(reg)[4]$coefficients)
                }
                else{
                  reg = lm(percentIsolation ~ homophilyC + degreeD, data=df.netIntLowDegree[df.netIntLowDegree$coopFrac==key,])
                  print(paste("Regression on proportion of ever-isolated individuals, degree %ile = ",key," ; ",sep=""))
                  print(summary(reg)[4]$coefficients)
                }
              }
    )
    
    
    
    #initial D-assortativity     
    plotList <- lapply(
              unique(df.netIntLowDegree$coopFrac),
              function(key) {
                if(key==0){
                  ggplot(data = df.netIntLowDegree[df.netIntLowDegree$coopFrac==key,], aes(x = homophilyD, y = percentIsolation)) + 
                      geom_point() +
                      scale_x_continuous(paste("D-assortativity, ","Control",sep="")) + 
                      scale_y_continuous("Proportion isolated") +
                      geom_smooth(method='lm', formula= y~x) + 
                      stat_cor(method = "pearson")
                }
                else{
                  ggplot(data = df.netIntLowDegree[df.netIntLowDegree$coopFrac==key,], aes(x = homophilyD, y = percentIsolation)) + 
                      geom_point() +
                      scale_x_continuous(paste("D-assortativity, degree %ile = ",key,sep="")) + 
                      scale_y_continuous("Proportion isolated") +
                      geom_smooth(method='lm', formula= y~x) + 
                      stat_cor(method = "pearson")
                }
              }
    )
    plot= ggarrange(plotlist=plotList)
    print(annotate_figure(plot, top = text_grob(paste("Proportion of ever-isolated individuals, ","V=",V,", Gini=", GINI, sep=""), color = "black", face = "bold", size = 10)))
    
    lapply(unique(df.netIntLowDegree$coopFrac),
              function(key) {
                if(key==0){
                  reg = lm(percentIsolation ~ homophilyD + degreeD, data=df.netIntLowDegree[df.netIntLowDegree$coopFrac==key,])
                  print(paste("Regression on proportion of ever-isolated individuals, ","Control"," ; ",sep=""))
                  print(summary(reg)[4]$coefficients)
                }
                else{
                  reg = lm(percentIsolation ~ homophilyD + degreeD, data=df.netIntLowDegree[df.netIntLowDegree$coopFrac==key,])
                  print(paste("Regression on proportion of ever-isolated individuals, degree %ile = ",key," ; ",sep=""))
                  print(summary(reg)[4]$coefficients)
                }
              }
    )
    
    }
}
## Loading data last updated on  2023-01-20 20:37:15 
## Call model1.invisible(redo=TRUE) to update data.
## Loading data last updated on  2023-01-20 20:39:47 
## Call model2.invisible(redo=TRUE) to update data.
## Loading data last updated on  2023-01-20 22:02:59 
## Call model3(redo=TRUE) to update data.

## [1] "Regression on proportion of ever-isolated individuals, Control ; "
##                Estimate  Std. Error   t value     Pr(>|t|)
## (Intercept)  0.13094605 0.015391441  8.507719 2.101450e-16
## homophilyC   0.03644969 0.031788405  1.146635 2.520843e-01
## degreeD     -0.01669896 0.002518665 -6.630083 8.763707e-11
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.25 ; "
##                Estimate  Std. Error   t value     Pr(>|t|)
## (Intercept)  0.15929559 0.013667173 11.655343 6.402756e-28
## homophilyC   0.04400513 0.038720774  1.136473 2.563062e-01
## degreeD     -0.02148701 0.003376246 -6.364172 4.465523e-10
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.5 ; "
##                Estimate  Std. Error    t value     Pr(>|t|)
## (Intercept)  0.14917308 0.016242057  9.1843709 1.119523e-18
## homophilyC  -0.01686787 0.040388874 -0.4176366 6.763932e-01
## degreeD     -0.01795882 0.003742569 -4.7985269 2.116978e-06
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.75 ; "
##                Estimate  Std. Error   t value     Pr(>|t|)
## (Intercept)  0.14183548 0.015435903  9.188674 1.081901e-18
## homophilyC   0.02139177 0.035342637  0.605268 5.452772e-01
## degreeD     -0.01889306 0.003145342 -6.006678 3.661539e-09
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 1 ; "
##                Estimate  Std. Error    t value     Pr(>|t|)
## (Intercept)  0.12196768 0.014381708  8.4807506 2.573721e-16
## homophilyC  -0.00393277 0.031109054 -0.1264188 8.994515e-01
## degreeD     -0.01331617 0.002511203 -5.3027044 1.720048e-07
## Warning: Removed 2 rows containing non-finite values (`stat_smooth()`).
## Warning: Removed 2 rows containing non-finite values (`stat_cor()`).
## Warning: Removed 2 rows containing missing values (`geom_point()`).
## Warning: Removed 6 rows containing non-finite values (`stat_smooth()`).
## Warning: Removed 6 rows containing non-finite values (`stat_cor()`).
## Warning: Removed 6 rows containing missing values (`geom_point()`).
## Warning: Removed 3 rows containing non-finite values (`stat_smooth()`).
## Warning: Removed 3 rows containing non-finite values (`stat_cor()`).
## Warning: Removed 3 rows containing missing values (`geom_point()`).
## Warning: Removed 1 rows containing non-finite values (`stat_smooth()`).
## Warning: Removed 1 rows containing non-finite values (`stat_cor()`).
## Warning: Removed 1 rows containing missing values (`geom_point()`).

## [1] "Regression on proportion of ever-isolated individuals, Control ; "
##                Estimate  Std. Error   t value     Pr(>|t|)
## (Intercept)  0.15040992 0.012873243 11.683918 5.057272e-28
## homophilyD   0.05549179 0.022982577  2.414516 1.611781e-02
## degreeD     -0.02187415 0.003364019 -6.502385 1.934962e-10
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.25 ; "
##                Estimate  Std. Error   t value     Pr(>|t|)
## (Intercept)  0.17775673 0.012572059 14.139030 2.544073e-38
## homophilyD  -0.03307323 0.019330917 -1.710898 8.773155e-02
## degreeD     -0.01994542 0.003180323 -6.271507 7.847960e-10
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.5 ; "
##                 Estimate  Std. Error    t value     Pr(>|t|)
## (Intercept)  0.144889523 0.015911044  9.1062236 2.115427e-18
## homophilyD   0.006685127 0.020123425  0.3322062 7.398745e-01
## degreeD     -0.018540299 0.003494191 -5.3060352 1.694663e-07
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.75 ; "
##                 Estimate  Std. Error    t value     Pr(>|t|)
## (Intercept)  0.145537263 0.014840529  9.8067437 7.188465e-21
## homophilyD   0.004590288 0.017220116  0.2665655 7.899145e-01
## degreeD     -0.018605908 0.003002486 -6.1968334 1.212145e-09
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 1 ; "
##                 Estimate  Std. Error    t value     Pr(>|t|)
## (Intercept)  0.122134693 0.014079176  8.6748464 5.921592e-17
## homophilyD  -0.008454762 0.016594236 -0.5094999 6.106280e-01
## degreeD     -0.013118368 0.002380298 -5.5112286 5.731362e-08
## Loading data last updated on  2023-01-20 21:50:22 
## Call model1.visible(redo=TRUE) to update data.
## Loading data last updated on  2023-01-20 21:54:00 
## Call model2.visible(redo=TRUE) to update data.
## Loading data last updated on  2023-01-20 22:02:59 
## Call model3(redo=TRUE) to update data.

## [1] "Regression on proportion of ever-isolated individuals, Control ; "
##                Estimate  Std. Error   t value     Pr(>|t|)
## (Intercept)  0.15628044 0.015209534 10.275163 1.376723e-22
## homophilyC  -0.07719520 0.030465524 -2.533854 1.158765e-02
## degreeD     -0.01923433 0.002560284 -7.512577 2.714556e-13
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.25 ; "
##                Estimate  Std. Error   t value     Pr(>|t|)
## (Intercept)  0.17933049 0.013959562 12.846427 8.108978e-33
## homophilyC  -0.05874912 0.039255913 -1.496567 1.351406e-01
## degreeD     -0.02485006 0.003465081 -7.171569 2.704708e-12
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.5 ; "
##                Estimate  Std. Error   t value     Pr(>|t|)
## (Intercept)  0.11065842 0.012956334  8.540875 1.636822e-16
## homophilyC  -0.04857804 0.030633915 -1.585760 1.134297e-01
## degreeD     -0.01279233 0.003106348 -4.118124 4.473043e-05
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.75 ; "
##                Estimate  Std. Error   t value     Pr(>|t|)
## (Intercept)  0.13235058 0.011891981 11.129397 7.676709e-26
## homophilyC  -0.08577792 0.028190330 -3.042814 2.467794e-03
## degreeD     -0.01546635 0.002593746 -5.962940 4.704454e-09
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 1 ; "
##                 Estimate  Std. Error    t value     Pr(>|t|)
## (Intercept)  0.093902262 0.010862269  8.6448108 7.444935e-17
## homophilyC   0.002985536 0.024878286  0.1200057 9.045271e-01
## degreeD     -0.012224929 0.001921196 -6.3631872 4.492087e-10
## Warning: Removed 1 rows containing non-finite values (`stat_smooth()`).
## Warning: Removed 1 rows containing non-finite values (`stat_cor()`).
## Warning: Removed 1 rows containing missing values (`geom_point()`).
## Warning: Removed 1 rows containing non-finite values (`stat_smooth()`).
## Warning: Removed 1 rows containing non-finite values (`stat_cor()`).
## Warning: Removed 1 rows containing missing values (`geom_point()`).
## Warning: Removed 1 rows containing non-finite values (`stat_smooth()`).
## Warning: Removed 1 rows containing non-finite values (`stat_cor()`).
## Warning: Removed 1 rows containing missing values (`geom_point()`).

## [1] "Regression on proportion of ever-isolated individuals, Control ; "
##                 Estimate  Std. Error    t value     Pr(>|t|)
## (Intercept)  0.135120739 0.013274051 10.1793145 3.144708e-22
## homophilyD  -0.009977077 0.021223189 -0.4701026 6.384883e-01
## degreeD     -0.019018199 0.003308541 -5.7482134 1.577139e-08
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.25 ; "
##                Estimate  Std. Error     t value     Pr(>|t|)
## (Intercept)  0.16920819 0.012836095 13.18221715 3.056794e-34
## homophilyD   0.00046853 0.020746163  0.02258394 9.819912e-01
## degreeD     -0.02681948 0.003283008 -8.16918045 2.588055e-15
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.5 ; "
##                Estimate  Std. Error    t value     Pr(>|t|)
## (Intercept)  0.10883643 0.012950432  8.4040777 4.588399e-16
## homophilyD  -0.00862014 0.015080199 -0.5716198 5.678385e-01
## degreeD     -0.01507841 0.002821429 -5.3442470 1.386859e-07
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.75 ; "
##                Estimate Std. Error   t value     Pr(>|t|)
## (Intercept)  0.12685019 0.01188549 10.672691 4.409657e-24
## homophilyD  -0.01557184 0.01441668 -1.080127 2.806096e-01
## degreeD     -0.01857386 0.00237091 -7.834062 2.885170e-14
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 1 ; "
##                 Estimate  Std. Error    t value     Pr(>|t|)
## (Intercept)  0.092697504 0.010791660  8.5897351 1.136520e-16
## homophilyD   0.008294383 0.011663041  0.7111681 4.773144e-01
## degreeD     -0.012284491 0.001758523 -6.9856874 9.164859e-12
## Loading data last updated on  2023-01-20 20:37:15 
## Call model1.invisible(redo=TRUE) to update data.
## Loading data last updated on  2023-01-20 20:39:47 
## Call model2.invisible(redo=TRUE) to update data.
## Loading data last updated on  2023-01-20 22:02:59 
## Call model3(redo=TRUE) to update data.

## [1] "Regression on proportion of ever-isolated individuals, Control ; "
##                Estimate  Std. Error    t value     Pr(>|t|)
## (Intercept)  0.15984723 0.015651165 10.2131202 2.338163e-22
## homophilyC  -0.01616286 0.030172210 -0.5356871 5.924145e-01
## degreeD     -0.01930176 0.002661673 -7.2517427 1.587095e-12
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.25 ; "
##                Estimate  Std. Error    t value     Pr(>|t|)
## (Intercept)  0.15257545 0.013863511 11.0055424 2.325939e-25
## homophilyC  -0.02268377 0.038334921 -0.5917259 5.543032e-01
## degreeD     -0.01419057 0.003287644 -4.3163328 1.915332e-05
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.5 ; "
##                 Estimate  Std. Error    t value     Pr(>|t|)
## (Intercept)  0.188827841 0.015465015 12.2100002 3.604540e-30
## homophilyC   0.005388759 0.037901183  0.1421792 8.869961e-01
## degreeD     -0.028549195 0.003590695 -7.9508825 1.255537e-14
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.75 ; "
##                Estimate  Std. Error    t value     Pr(>|t|)
## (Intercept)  0.14988970 0.014407488 10.4035976 4.569631e-23
## homophilyC  -0.03092540 0.035263216 -0.8769877 3.809170e-01
## degreeD     -0.01798433 0.003131484 -5.7430697 1.620994e-08
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 1 ; "
##                 Estimate  Std. Error   t value     Pr(>|t|)
## (Intercept)  0.094191695 0.014049282  6.704378 5.507816e-11
## homophilyC  -0.076512316 0.031608669 -2.420612 1.585180e-02
## degreeD     -0.005251573 0.002549996 -2.059444 3.997204e-02
## Warning: Removed 1 rows containing non-finite values (`stat_smooth()`).
## Warning: Removed 1 rows containing non-finite values (`stat_cor()`).
## Warning: Removed 1 rows containing missing values (`geom_point()`).
## Warning: Removed 2 rows containing non-finite values (`stat_smooth()`).
## Warning: Removed 2 rows containing non-finite values (`stat_cor()`).
## Warning: Removed 2 rows containing missing values (`geom_point()`).
## Warning: Removed 3 rows containing non-finite values (`stat_smooth()`).
## Warning: Removed 3 rows containing non-finite values (`stat_cor()`).
## Warning: Removed 3 rows containing missing values (`geom_point()`).
## Warning: Removed 3 rows containing non-finite values (`stat_smooth()`).
## Warning: Removed 3 rows containing non-finite values (`stat_cor()`).
## Warning: Removed 3 rows containing missing values (`geom_point()`).

## [1] "Regression on proportion of ever-isolated individuals, Control ; "
##                 Estimate  Std. Error    t value     Pr(>|t|)
## (Intercept)  0.155951039 0.013128898 11.8784559 8.096727e-29
## homophilyD   0.007362652 0.021002682  0.3505577 7.260687e-01
## degreeD     -0.019975194 0.003217569 -6.2081642 1.132158e-09
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.25 ; "
##                Estimate  Std. Error   t value     Pr(>|t|)
## (Intercept)  0.15752111 0.012382616 12.721150 2.776675e-32
## homophilyD  -0.03044114 0.017600408 -1.729570 8.432925e-02
## degreeD     -0.01477887 0.003108468 -4.754388 2.612368e-06
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.5 ; "
##                 Estimate  Std. Error    t value     Pr(>|t|)
## (Intercept)  0.188495454 0.015040862 12.5322243 1.737758e-31
## homophilyD   0.002664551 0.018334258  0.1453318 8.845081e-01
## degreeD     -0.028246836 0.003308803 -8.5368749 1.702630e-16
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.75 ; "
##                Estimate  Std. Error   t value     Pr(>|t|)
## (Intercept)  0.14731822 0.014060065 10.477777 2.477474e-23
## homophilyD   0.02300251 0.017474468  1.316349 1.886672e-01
## degreeD     -0.02062891 0.002928411 -7.044405 6.283617e-12
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 1 ; "
##                 Estimate  Std. Error    t value     Pr(>|t|)
## (Intercept)  0.092635910 0.014330623  6.4641929 2.447773e-10
## homophilyD  -0.012224001 0.017230266 -0.7094493 4.783804e-01
## degreeD     -0.008111276 0.002315605 -3.5028751 5.020622e-04
## Loading data last updated on  2023-01-20 21:50:22 
## Call model1.visible(redo=TRUE) to update data.
## Loading data last updated on  2023-01-20 21:54:00 
## Call model2.visible(redo=TRUE) to update data.
## Loading data last updated on  2023-01-20 22:02:59 
## Call model3(redo=TRUE) to update data.

## [1] "Regression on proportion of ever-isolated individuals, Control ; "
##                Estimate  Std. Error   t value     Pr(>|t|)
## (Intercept)  0.15338576 0.014446926 10.617190 7.164005e-24
## homophilyC  -0.08317474 0.030214888 -2.752774 6.125454e-03
## degreeD     -0.01840546 0.002370567 -7.764159 4.725773e-14
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.25 ; "
##                Estimate Std. Error    t value     Pr(>|t|)
## (Intercept)  0.15808198 0.01363921 11.5902590 1.165618e-27
## homophilyC  -0.02759612 0.03973788 -0.6944536 4.877223e-01
## degreeD     -0.02196114 0.00328485 -6.6855829 6.196929e-11
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.5 ; "
##                Estimate  Std. Error    t value     Pr(>|t|)
## (Intercept)  0.15005767 0.012086826 12.4149775 5.146723e-31
## homophilyC   0.01005551 0.029309780  0.3430769 7.316857e-01
## degreeD     -0.02588229 0.002699184 -9.5889332 4.292732e-20
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.75 ; "
##                Estimate  Std. Error    t value     Pr(>|t|)
## (Intercept)  0.12452478 0.012547734  9.9240857 2.683589e-21
## homophilyC  -0.02234361 0.030400346 -0.7349789 4.626990e-01
## degreeD     -0.01770556 0.002779141 -6.3708759 4.288735e-10
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 1 ; "
##                 Estimate  Std. Error   t value     Pr(>|t|)
## (Intercept)  0.088190045 0.011166359  7.897833 1.834061e-14
## homophilyC   0.003751065 0.024263978  0.154594 8.772042e-01
## degreeD     -0.011298652 0.002045596 -5.523403 5.369330e-08
## Warning: Removed 2 rows containing non-finite values (`stat_smooth()`).
## Warning: Removed 2 rows containing non-finite values (`stat_cor()`).
## Warning: Removed 2 rows containing missing values (`geom_point()`).
## Warning: Removed 2 rows containing non-finite values (`stat_smooth()`).
## Warning: Removed 2 rows containing non-finite values (`stat_cor()`).
## Warning: Removed 2 rows containing missing values (`geom_point()`).
## Warning: Removed 2 rows containing non-finite values (`stat_smooth()`).
## Warning: Removed 2 rows containing non-finite values (`stat_cor()`).
## Warning: Removed 2 rows containing missing values (`geom_point()`).
## Warning: Removed 1 rows containing non-finite values (`stat_smooth()`).
## Warning: Removed 1 rows containing non-finite values (`stat_cor()`).
## Warning: Removed 1 rows containing missing values (`geom_point()`).

## [1] "Regression on proportion of ever-isolated individuals, Control ; "
##                  Estimate  Std. Error     t value     Pr(>|t|)
## (Intercept)  0.1344876386 0.012345763 10.89342452 6.443580e-25
## homophilyD   0.0002429665 0.020292774  0.01197306 9.904519e-01
## degreeD     -0.0196499091 0.003032845 -6.47903448 2.232063e-10
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.25 ; "
##                Estimate  Std. Error   t value     Pr(>|t|)
## (Intercept)  0.16219463 0.012234920 13.256697 1.469344e-34
## homophilyD  -0.04208426 0.018721050 -2.247965 2.501604e-02
## degreeD     -0.02185525 0.003061094 -7.139686 3.339118e-12
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.5 ; "
##                 Estimate  Std. Error    t value     Pr(>|t|)
## (Intercept)  0.152132102 0.011532976 13.1910534 2.921454e-34
## homophilyD  -0.003412912 0.016528689 -0.2064841 8.364977e-01
## degreeD     -0.025412931 0.002591814 -9.8050762 7.344069e-21
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.75 ; "
##                Estimate  Std. Error    t value     Pr(>|t|)
## (Intercept)  0.12207965 0.012499575  9.7667040 1.009193e-20
## homophilyD   0.01060301 0.015777367  0.6720393 5.018722e-01
## degreeD     -0.01916621 0.002527913 -7.5818309 1.695149e-13
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 1 ; "
##                  Estimate  Std. Error      t value     Pr(>|t|)
## (Intercept)  8.900748e-02 0.011161549  7.974473687 1.063994e-14
## homophilyD   5.811643e-05 0.012573913  0.004621985 9.963141e-01
## degreeD     -1.124175e-02 0.001865629 -6.025716089 3.285802e-09
## Loading data last updated on  2023-01-20 20:37:15 
## Call model1.invisible(redo=TRUE) to update data.
## Loading data last updated on  2023-01-20 20:39:47 
## Call model2.invisible(redo=TRUE) to update data.
## Loading data last updated on  2023-01-20 22:02:59 
## Call model3(redo=TRUE) to update data.

## Warning: Removed 1 rows containing non-finite values (`stat_summary()`).
## Warning: Removed 1 rows containing non-finite values (`stat_compare_means()`).

## [1] "Regression on proportion of ever-isolated individuals, Control ; "
##                Estimate  Std. Error   t value     Pr(>|t|)
## (Intercept)  0.15432359 0.015920456  9.693415 1.821030e-20
## homophilyC  -0.05376122 0.030714569 -1.750349 8.067515e-02
## degreeD     -0.01557557 0.002595076 -6.001970 3.761936e-09
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.25 ; "
##                 Estimate  Std. Error     t value     Pr(>|t|)
## (Intercept)  0.136055435 0.012811078 10.62013979 6.981878e-24
## homophilyC  -0.003643859 0.036789991 -0.09904484 9.211426e-01
## degreeD     -0.012125782 0.003084838 -3.93076757 9.668473e-05
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.5 ; "
##                Estimate  Std. Error   t value     Pr(>|t|)
## (Intercept)  0.15026797 0.014613828 10.282588 1.291986e-22
## homophilyC  -0.03939228 0.034583628 -1.139044 2.552334e-01
## degreeD     -0.01694288 0.003477802 -4.871722 1.489745e-06
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.75 ; "
##                Estimate  Std. Error   t value     Pr(>|t|)
## (Intercept)  0.14188694 0.015997152  8.869513 1.324785e-17
## homophilyC  -0.10350128 0.033408794 -3.098025 2.058396e-03
## degreeD     -0.01171553 0.003379536 -3.466610 5.727631e-04
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 1 ; "
##                 Estimate  Std. Error    t value     Pr(>|t|)
## (Intercept)  0.091464620 0.014255501  6.4160932 3.268272e-10
## homophilyC  -0.004543673 0.028161759 -0.1613419 8.718898e-01
## degreeD     -0.008652832 0.002386302 -3.6260426 3.175568e-04
## Warning: Removed 2 rows containing non-finite values (`stat_smooth()`).
## Warning: Removed 2 rows containing non-finite values (`stat_cor()`).
## Warning: Removed 2 rows containing missing values (`geom_point()`).
## Warning: Removed 1 rows containing non-finite values (`stat_smooth()`).
## Warning: Removed 1 rows containing non-finite values (`stat_cor()`).
## Warning: Removed 1 rows containing missing values (`geom_point()`).
## Warning: Removed 2 rows containing non-finite values (`stat_smooth()`).
## Warning: Removed 2 rows containing non-finite values (`stat_cor()`).
## Warning: Removed 2 rows containing missing values (`geom_point()`).
## Warning: Removed 2 rows containing non-finite values (`stat_smooth()`).
## Warning: Removed 2 rows containing non-finite values (`stat_cor()`).
## Warning: Removed 2 rows containing missing values (`geom_point()`).

## [1] "Regression on proportion of ever-isolated individuals, Control ; "
##                Estimate  Std. Error    t value     Pr(>|t|)
## (Intercept)  0.13961222 0.012950817 10.7801869 1.715215e-24
## homophilyD   0.01810996 0.021641238  0.8368263 4.030924e-01
## degreeD     -0.01699796 0.003201434 -5.3094838 1.660597e-07
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.25 ; "
##                Estimate  Std. Error    t value     Pr(>|t|)
## (Intercept)  0.13944377 0.011569026 12.0531983 1.628805e-29
## homophilyD  -0.01053831 0.018959385 -0.5558358 5.785742e-01
## degreeD     -0.01241918 0.002949085 -4.2111982 3.018141e-05
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.5 ; "
##                 Estimate  Std. Error    t value     Pr(>|t|)
## (Intercept)  0.147830149 0.014496039 10.1979683 2.683378e-22
## homophilyD   0.002596155 0.019147925  0.1355841 8.922051e-01
## degreeD     -0.019225848 0.003199755 -6.0085381 3.627206e-09
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.75 ; "
##                Estimate  Std. Error   t value     Pr(>|t|)
## (Intercept)  0.13088448 0.016037901  8.160948 2.770110e-15
## homophilyD   0.00819453 0.018963860  0.432113 6.658475e-01
## degreeD     -0.01633077 0.003164956 -5.159873 3.582873e-07
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 1 ; "
##                  Estimate  Std. Error     t value     Pr(>|t|)
## (Intercept)  0.0904448860 0.013846748  6.53185019 1.614885e-10
## homophilyD   0.0008452342 0.014614724  0.05783443 9.539039e-01
## degreeD     -0.0087406087 0.002337155 -3.73984979 2.056622e-04
## Loading data last updated on  2023-01-20 21:50:22 
## Call model1.visible(redo=TRUE) to update data.
## Loading data last updated on  2023-01-20 21:54:00 
## Call model2.visible(redo=TRUE) to update data.
## Loading data last updated on  2023-01-20 22:02:59 
## Call model3(redo=TRUE) to update data.

## [1] "Regression on proportion of ever-isolated individuals, Control ; "
##                 Estimate  Std. Error    t value     Pr(>|t|)
## (Intercept)  0.108817271 0.013735347  7.9224259 1.538926e-14
## homophilyC   0.003311191 0.026046381  0.1271267 8.988915e-01
## degreeD     -0.015253432 0.002342085 -6.5127583 1.809537e-10
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.25 ; "
##                Estimate  Std. Error   t value     Pr(>|t|)
## (Intercept)  0.15304931 0.012532319 12.212369 3.524694e-30
## homophilyC  -0.07926105 0.036367324 -2.179458 2.976643e-02
## degreeD     -0.01663318 0.003027325 -5.494348 6.272820e-08
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.5 ; "
##                Estimate  Std. Error   t value     Pr(>|t|)
## (Intercept)  0.11591286 0.012048910  9.620195 3.323416e-20
## homophilyC   0.01304985 0.029519548  0.442075 6.586272e-01
## degreeD     -0.01859602 0.002795488 -6.652157 7.637373e-11
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.75 ; "
##                Estimate  Std. Error    t value     Pr(>|t|)
## (Intercept)  0.13321824 0.011669088 11.4163369 5.725682e-27
## homophilyC   0.01263887 0.028013489  0.4511709 6.520631e-01
## degreeD     -0.02210541 0.002678293 -8.2535444 1.393972e-15
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 1 ; "
##                Estimate  Std. Error    t value     Pr(>|t|)
## (Intercept)  0.08670680 0.010049985  8.6275559 8.489183e-17
## homophilyC  -0.01254645 0.022245345 -0.5640036 5.730061e-01
## degreeD     -0.01053555 0.001678127 -6.2781583 7.475417e-10
## Warning: Removed 1 rows containing non-finite values (`stat_smooth()`).
## Warning: Removed 1 rows containing non-finite values (`stat_cor()`).
## Warning: Removed 1 rows containing missing values (`geom_point()`).
## Warning: Removed 2 rows containing non-finite values (`stat_smooth()`).
## Warning: Removed 2 rows containing non-finite values (`stat_cor()`).
## Warning: Removed 2 rows containing missing values (`geom_point()`).

## [1] "Regression on proportion of ever-isolated individuals, Control ; "
##                 Estimate  Std. Error    t value     Pr(>|t|)
## (Intercept)  0.109239981 0.011574354  9.4381057 1.464129e-19
## homophilyD  -0.004675183 0.017538257 -0.2665706 7.899104e-01
## degreeD     -0.014840672 0.002800269 -5.2997303 1.746776e-07
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.25 ; "
##                Estimate  Std. Error    t value     Pr(>|t|)
## (Intercept)  0.13728439 0.011726629 11.7070637 4.027841e-28
## homophilyD   0.00852464 0.018761210  0.4543758 6.497571e-01
## degreeD     -0.01945080 0.002813202 -6.9141127 1.455112e-11
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.5 ; "
##                Estimate  Std. Error    t value     Pr(>|t|)
## (Intercept)  0.11746650 0.011750716  9.9965398 1.485640e-21
## homophilyD   0.00385425 0.015036013  0.2563346 7.977990e-01
## degreeD     -0.01831306 0.002576214 -7.1085158 4.119556e-12
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.75 ; "
##                Estimate  Std. Error    t value     Pr(>|t|)
## (Intercept)  0.13311324 0.011577477 11.4976041 2.726200e-27
## homophilyD   0.01468363 0.014906214  0.9850679 3.250700e-01
## degreeD     -0.02222249 0.002427624 -9.1540091 1.424433e-18
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 1 ; "
##                 Estimate  Std. Error   t value     Pr(>|t|)
## (Intercept)  0.085238547 0.009679468  8.806119 2.162898e-17
## homophilyD  -0.001715535 0.010371471 -0.165409 8.686893e-01
## degreeD     -0.010818440 0.001605082 -6.740117 4.398594e-11
plot.trends <- 
  data.frame(
    trends.df %>% 
      group_by(round, V, GINI, fractionCoop) %>% 
      summarize_all(list(mean=~mean(., na.rm=TRUE),sd=~sd(., na.rm=TRUE)))
  )

plot.trends$V = factor(plot.trends$V)
plot.trends$GINI = factor(plot.trends$GINI)

for(i in unique(plot.trends$fractionCoop)){
  g.gini = ggplot(data=plot.trends[plot.trends$fractionCoop==i,], aes(x=round,y=gini_mean,group=interaction(GINI,V))) +
  geom_line(aes(color=GINI,linetype=V)) +
  geom_ribbon(aes(ymin = gini_mean - gini_sd, ymax = gini_mean + gini_sd, fill=GINI),alpha=0.3) +
  xlab("Round")+
  ylab("gini") +
  theme_bw() 

  g.gmd = ggplot(data=plot.trends[plot.trends$fractionCoop==i,], aes(x=round,y=gmd_mean,group=interaction(GINI,V))) +
    geom_line(aes(color=GINI,linetype=V)) +
    geom_ribbon(aes(ymin = gmd_mean - gmd_sd, ymax = gmd_mean + gmd_sd, fill=GINI),alpha=0.3) +
    xlab("Round")+
    ylab("gmd") +
    theme_bw() 
  
  g.avg_wealth = ggplot(data=plot.trends[plot.trends$fractionCoop==i,], aes(x=round,y=avg_wealth_mean,group=interaction(GINI,V))) +
    geom_line(aes(color=GINI,linetype=V)) +
    geom_ribbon(aes(ymin = avg_wealth_mean - avg_wealth_sd, ymax = avg_wealth_mean + avg_wealth_sd, fill=GINI),alpha=0.3) +
    xlab("Round")+
    ylab("avg_wealth") +
    theme_bw() 
  
  g.avg_coop = ggplot(data=plot.trends[plot.trends$fractionCoop==i,], aes(x=round,y=avg_coop_mean,group=interaction(GINI,V))) +
    geom_line(aes(color=GINI,linetype=V)) +
    geom_ribbon(aes(ymin = avg_coop_mean - avg_coop_sd, ymax = avg_coop_mean + avg_coop_sd, fill=GINI),alpha=0.3) +
    xlab("Round")+
    ylab("avg_coop") +
    theme_bw() 
  
  g.avg_degree = ggplot(data=plot.trends[plot.trends$fractionCoop==i,], aes(x=round,y=avg_degree_mean,group=interaction(GINI,V))) +
    geom_line(aes(color=GINI,linetype=V)) +
    geom_ribbon(aes(ymin = avg_degree_mean - avg_degree_sd, ymax = avg_degree_mean + avg_degree_sd, fill=GINI),alpha=0.3) +
    xlab("Round")+
    ylab("avg_degree") +
    theme_bw() 
   
  
  
  plot <- ggarrange(g.gini,g.gmd,g.avg_wealth,g.avg_coop,g.avg_degree,common.legend = TRUE,legend="bottom")
  print(annotate_figure(plot, top = text_grob(paste("Eigenvector centrality percentile of nodes assigned to defectors =",i), color = "black", face = "bold", size = 10)))
}
## Warning: Removed 6 rows containing missing values (`geom_line()`).
## Warning: Removed 6 rows containing missing values (`geom_line()`).

## Warning: Removed 6 rows containing missing values (`geom_line()`).

## Warning: Removed 6 rows containing missing values (`geom_line()`).

## Warning: Removed 6 rows containing missing values (`geom_line()`).

fig1 = ggplot(data = df.netIntLowDegree, 
                         aes(x = degreeD, y = homophilyC, color = percentIsolation*100)) + 
  geom_point() +
  scale_x_continuous("Mean degree of defectors") + 
  scale_y_continuous("C-assortativity") +  
  scale_color_viridis(option = "magma") +
  labs(color="Isolated \nindividuals (%)")

fig2 = ggplot(data = df.netIntLowDegree, 
                         aes(x = degreeD, y = homophilyD, color = percentIsolation*100)) + 
  geom_point() +
  scale_x_continuous("Mean degree of defectors") + 
  scale_y_continuous("D-assortativity") +  
  scale_color_viridis(option = "magma") +
  labs(color="Isolated \nindividuals (%)")

fig3 = ggplot(data = df.netIntLowDegree, 
                         aes(x = degreeD, y = heterophily, color = percentIsolation*100)) + 
  geom_point() +
  scale_x_continuous("Mean degree of defectors") + 
  scale_y_continuous("Heterophily") +  
  scale_color_viridis(option = "magma") +
  labs(color="Isolated \nindividuals (%)")

fig4 = ggplot(data = df.netIntLowDegree, 
                         aes(x = degreeC, y = homophilyC, color = percentIsolation*100)) + 
  geom_point() +
  scale_x_continuous("Mean degree of cooperators") + 
  scale_y_continuous("C-assortativity") +  
  scale_color_viridis(option = "magma") +
  labs(color="Isolated \nindividuals (%)")

fig5 = ggplot(data = df.netIntLowDegree, 
                         aes(x = degreeC, y = homophilyD, color = percentIsolation*100)) + 
  geom_point() +
  scale_x_continuous("Mean degree of cooperators") + 
  scale_y_continuous("D-assortativity") +  
  scale_color_viridis(option = "magma") +
  labs(color="Isolated \nindividuals (%)")


fig6 = ggplot(data = df.netIntLowDegree, 
                         aes(x = degreeC, y = heterophily, color = percentIsolation*100)) + 
  geom_point() +
  scale_x_continuous("Mean degree of cooperators") + 
  scale_y_continuous("Heterophily") +  
  scale_color_viridis(option = "magma") +
  labs(color="Isolated \nindividuals (%)")

fig7 = ggplot(data = df.netIntLowDegree, 
                         aes(x = degreeC, y = degreeD, color = percentIsolation*100)) + 
  geom_point() +
  scale_x_continuous("Mean degree of cooperators") + 
  scale_y_continuous("Mean degree of defectors") +  
  scale_color_viridis(option = "magma") +
  labs(color="Isolated \nindividuals (%)")

print(ggarrange(fig1,fig2,fig3,fig4,fig5,fig6,fig7,common.legend = TRUE,legend="right"))
## Warning: Removed 3 rows containing missing values (`geom_point()`).
## Removed 3 rows containing missing values (`geom_point()`).

fig1 = ggplot(data = df.netIntLowDegree, 
                         aes(x = degreeC, y = percentIsolation*100)) + 
  geom_point() +
  scale_x_continuous("Mean degree of cooperators") + 
  scale_y_continuous("Isolated individuals (%)") 


fig2 = ggplot(data = df.netIntLowDegree, 
                         aes(x = degreeD, y = percentIsolation*100)) + 
  geom_point() +
  scale_x_continuous("Mean degree of defectors") + 
  scale_y_continuous("Isolated individuals (%)") 


fig3 = ggplot(data = df.netIntLowDegree, 
                         aes(x = homophilyC, y = percentIsolation*100)) + 
  geom_point() +
  scale_x_continuous("C-assortativity") + 
  scale_y_continuous("Isolated individuals (%)") 



fig4 = ggplot(data = df.netIntLowDegree, 
                         aes(x = homophilyD, y = percentIsolation*100)) + 
  geom_point() +
  scale_x_continuous("D-assortativity") + 
  scale_y_continuous("Isolated individuals (%)") 



print(ggarrange(fig1,fig2,fig3,fig4,common.legend = TRUE,legend="right"))
## Warning: Removed 3 rows containing missing values (`geom_point()`).
## Removed 3 rows containing missing values (`geom_point()`).

reg.isolation = glm(percentIsolation*100 ~ degreeC + degreeD + homophilyC + homophilyD + heterophily, data=df.netIntLowDegree, family = gaussian(link = "identity"))
summary(reg.isolation)
## 
## Call:
## glm(formula = percentIsolation * 100 ~ degreeC + degreeD + homophilyC + 
##     homophilyD + heterophily, family = gaussian(link = "identity"), 
##     data = df.netIntLowDegree)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -8.7125  -3.2828  -0.8629   2.3187  25.0619  
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  13.1640     0.6504  20.240  < 2e-16 ***
## degreeC       0.2942     0.2079   1.415  0.15726    
## degreeD      -1.5886     0.1266 -12.552  < 2e-16 ***
## homophilyC   -3.1185     1.9339  -1.613  0.10698    
## homophilyD   -0.0140     0.7876  -0.018  0.98582    
## heterophily  -7.5558     2.8102  -2.689  0.00722 ** 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for gaussian family taken to be 19.10829)
## 
##     Null deviance: 58125  on 2496  degrees of freedom
## Residual deviance: 47599  on 2491  degrees of freedom
##   (3 observations deleted due to missingness)
## AIC: 14461
## 
## Number of Fisher Scoring iterations: 2
#variance inflation factor
car::vif(reg.isolation)
##     degreeC     degreeD  homophilyC  homophilyD heterophily 
##    4.135043    2.660549    2.585727    1.425332    3.419371
reg.isolation = glm(percentIsolation*100 ~ degreeD + homophilyD, data=df.netIntLowDegree, family = gaussian(link = "identity"))
summary(reg.isolation)
## 
## Call:
## glm(formula = percentIsolation * 100 ~ degreeD + homophilyD, 
##     family = gaussian(link = "identity"), data = df.netIntLowDegree)
## 
## Deviance Residuals: 
##    Min      1Q  Median      3Q     Max  
## -8.885  -3.370  -0.835   2.309  25.295  
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 12.26983    0.40247  30.486   <2e-16 ***
## degreeD     -1.82355    0.07955 -22.924   <2e-16 ***
## homophilyD   0.78632    0.67631   1.163    0.245    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for gaussian family taken to be 19.1556)
## 
##     Null deviance: 58125  on 2496  degrees of freedom
## Residual deviance: 47774  on 2494  degrees of freedom
##   (3 observations deleted due to missingness)
## AIC: 14464
## 
## Number of Fisher Scoring iterations: 2
#variance inflation factor
car::vif(reg.isolation)
##    degreeD homophilyD 
##   1.048436   1.048436
#double machine learning
library(DoubleML)
library(mlr3)
library(mlr3learners)
set.seed(3141)


##degreeC
dml_data = DoubleMLData$new(df.netIntLowDegree[complete.cases(df.netIntLowDegree[c("percentIsolation","degreeC","degreeD","homophilyC","homophilyD","heterophily")]),],
                             y_col = "percentIsolation",
                             d_cols = "degreeC",
                             x_cols = c("degreeD","homophilyC","homophilyD","heterophily"))
print(dml_data)
## ================= DoubleMLData Object ==================
## 
## 
## ------------------ Data summary      ------------------
## Outcome variable: percentIsolation
## Treatment variable(s): degreeC
## Covariates: degreeD, homophilyC, homophilyD, heterophily
## Instrument(s): 
## No. Observations: 2497
# surpress messages from mlr3 package during fitting
lgr::get_logger("mlr3")$set_threshold("warn")

learner = lrn("regr.ranger", num.trees=500, mtry=floor(sqrt(4)), max.depth=5, min.node.size=2)
ml_l = learner$clone()
ml_m = learner$clone()

obj_dml_plr = DoubleMLPLR$new(dml_data, ml_l=ml_l, ml_m=ml_m)
obj_dml_plr$fit()
print(obj_dml_plr)
## ================= DoubleMLPLR Object ==================
## 
## 
## ------------------ Data summary      ------------------
## Outcome variable: percentIsolation
## Treatment variable(s): degreeC
## Covariates: degreeD, homophilyC, homophilyD, heterophily
## Instrument(s): 
## No. Observations: 2497
## 
## ------------------ Score & algorithm ------------------
## Score function: partialling out
## DML algorithm: dml2
## 
## ------------------ Machine learner   ------------------
## ml_l: regr.ranger
## ml_m: regr.ranger
## 
## ------------------ Resampling        ------------------
## No. folds: 5
## No. repeated sample splits: 1
## Apply cross-fitting: TRUE
## 
## ------------------ Fit summary       ------------------
##  Estimates and significance testing of the effect of target variables
##         Estimate. Std. Error t value Pr(>|t|)  
## degreeC  0.003332   0.001791   1.861   0.0628 .
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##degreeD
dml_data = DoubleMLData$new(df.netIntLowDegree[complete.cases(df.netIntLowDegree[c("percentIsolation","degreeC","degreeD","homophilyC","homophilyD","heterophily")]),],
                             y_col = "percentIsolation",
                             d_cols = "degreeD",
                             x_cols = c("degreeC","homophilyC","homophilyD","heterophily"))
print(dml_data)
## ================= DoubleMLData Object ==================
## 
## 
## ------------------ Data summary      ------------------
## Outcome variable: percentIsolation
## Treatment variable(s): degreeD
## Covariates: degreeC, homophilyC, homophilyD, heterophily
## Instrument(s): 
## No. Observations: 2497
# surpress messages from mlr3 package during fitting
lgr::get_logger("mlr3")$set_threshold("warn")

learner = lrn("regr.ranger", num.trees=500, mtry=floor(sqrt(4)), max.depth=5, min.node.size=2)
ml_l = learner$clone()
ml_m = learner$clone()

obj_dml_plr = DoubleMLPLR$new(dml_data, ml_l=ml_l, ml_m=ml_m)
obj_dml_plr$fit()
print(obj_dml_plr)
## ================= DoubleMLPLR Object ==================
## 
## 
## ------------------ Data summary      ------------------
## Outcome variable: percentIsolation
## Treatment variable(s): degreeD
## Covariates: degreeC, homophilyC, homophilyD, heterophily
## Instrument(s): 
## No. Observations: 2497
## 
## ------------------ Score & algorithm ------------------
## Score function: partialling out
## DML algorithm: dml2
## 
## ------------------ Machine learner   ------------------
## ml_l: regr.ranger
## ml_m: regr.ranger
## 
## ------------------ Resampling        ------------------
## No. folds: 5
## No. repeated sample splits: 1
## Apply cross-fitting: TRUE
## 
## ------------------ Fit summary       ------------------
##  Estimates and significance testing of the effect of target variables
##         Estimate. Std. Error t value Pr(>|t|)    
## degreeD -0.016388   0.001092  -15.01   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##homophilyC
dml_data = DoubleMLData$new(df.netIntLowDegree[complete.cases(df.netIntLowDegree[c("percentIsolation","degreeC","degreeD","homophilyC","homophilyD","heterophily")]),],
                             y_col = "percentIsolation",
                             d_cols = "homophilyC",
                             x_cols = c("degreeC","degreeD","homophilyD","heterophily"))
print(dml_data)
## ================= DoubleMLData Object ==================
## 
## 
## ------------------ Data summary      ------------------
## Outcome variable: percentIsolation
## Treatment variable(s): homophilyC
## Covariates: degreeC, degreeD, homophilyD, heterophily
## Instrument(s): 
## No. Observations: 2497
# surpress messages from mlr3 package during fitting
lgr::get_logger("mlr3")$set_threshold("warn")

learner = lrn("regr.ranger", num.trees=500, mtry=floor(sqrt(4)), max.depth=5, min.node.size=2)
ml_l = learner$clone()
ml_m = learner$clone()

obj_dml_plr = DoubleMLPLR$new(dml_data, ml_l=ml_l, ml_m=ml_m)
obj_dml_plr$fit()
print(obj_dml_plr)
## ================= DoubleMLPLR Object ==================
## 
## 
## ------------------ Data summary      ------------------
## Outcome variable: percentIsolation
## Treatment variable(s): homophilyC
## Covariates: degreeC, degreeD, homophilyD, heterophily
## Instrument(s): 
## No. Observations: 2497
## 
## ------------------ Score & algorithm ------------------
## Score function: partialling out
## DML algorithm: dml2
## 
## ------------------ Machine learner   ------------------
## ml_l: regr.ranger
## ml_m: regr.ranger
## 
## ------------------ Resampling        ------------------
## No. folds: 5
## No. repeated sample splits: 1
## Apply cross-fitting: TRUE
## 
## ------------------ Fit summary       ------------------
##  Estimates and significance testing of the effect of target variables
##            Estimate. Std. Error t value Pr(>|t|)  
## homophilyC  -0.03356    0.01643  -2.043   0.0411 *
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##homophilyD
dml_data = DoubleMLData$new(df.netIntLowDegree[complete.cases(df.netIntLowDegree[c("percentIsolation","degreeC","degreeD","homophilyC","homophilyD","heterophily")]),],
                             y_col = "percentIsolation",
                             d_cols = "homophilyD",
                             x_cols = c("degreeC","degreeD","homophilyC","heterophily"))
print(dml_data)
## ================= DoubleMLData Object ==================
## 
## 
## ------------------ Data summary      ------------------
## Outcome variable: percentIsolation
## Treatment variable(s): homophilyD
## Covariates: degreeC, degreeD, homophilyC, heterophily
## Instrument(s): 
## No. Observations: 2497
# surpress messages from mlr3 package during fitting
lgr::get_logger("mlr3")$set_threshold("warn")

learner = lrn("regr.ranger", num.trees=500, mtry=floor(sqrt(4)), max.depth=5, min.node.size=2)
ml_l = learner$clone()
ml_m = learner$clone()

obj_dml_plr = DoubleMLPLR$new(dml_data, ml_l=ml_l, ml_m=ml_m)
obj_dml_plr$fit()
print(obj_dml_plr)
## ================= DoubleMLPLR Object ==================
## 
## 
## ------------------ Data summary      ------------------
## Outcome variable: percentIsolation
## Treatment variable(s): homophilyD
## Covariates: degreeC, degreeD, homophilyC, heterophily
## Instrument(s): 
## No. Observations: 2497
## 
## ------------------ Score & algorithm ------------------
## Score function: partialling out
## DML algorithm: dml2
## 
## ------------------ Machine learner   ------------------
## ml_l: regr.ranger
## ml_m: regr.ranger
## 
## ------------------ Resampling        ------------------
## No. folds: 5
## No. repeated sample splits: 1
## Apply cross-fitting: TRUE
## 
## ------------------ Fit summary       ------------------
##  Estimates and significance testing of the effect of target variables
##            Estimate. Std. Error t value Pr(>|t|)
## homophilyD 0.0006673  0.0067919   0.098    0.922
##heterophily
dml_data = DoubleMLData$new(df.netIntLowDegree[complete.cases(df.netIntLowDegree[c("percentIsolation","degreeC","degreeD","homophilyC","homophilyD","heterophily")]),],
                             y_col = "percentIsolation",
                             d_cols = "heterophily",
                             x_cols = c("degreeC","degreeD","homophilyC","homophilyD"))
print(dml_data)
## ================= DoubleMLData Object ==================
## 
## 
## ------------------ Data summary      ------------------
## Outcome variable: percentIsolation
## Treatment variable(s): heterophily
## Covariates: degreeC, degreeD, homophilyC, homophilyD
## Instrument(s): 
## No. Observations: 2497
# surpress messages from mlr3 package during fitting
lgr::get_logger("mlr3")$set_threshold("warn")

learner = lrn("regr.ranger", num.trees=500, mtry=floor(sqrt(4)), max.depth=5, min.node.size=2)
ml_l = learner$clone()
ml_m = learner$clone()

obj_dml_plr = DoubleMLPLR$new(dml_data, ml_l=ml_l, ml_m=ml_m)
obj_dml_plr$fit()
print(obj_dml_plr)
## ================= DoubleMLPLR Object ==================
## 
## 
## ------------------ Data summary      ------------------
## Outcome variable: percentIsolation
## Treatment variable(s): heterophily
## Covariates: degreeC, degreeD, homophilyC, homophilyD
## Instrument(s): 
## No. Observations: 2497
## 
## ------------------ Score & algorithm ------------------
## Score function: partialling out
## DML algorithm: dml2
## 
## ------------------ Machine learner   ------------------
## ml_l: regr.ranger
## ml_m: regr.ranger
## 
## ------------------ Resampling        ------------------
## No. folds: 5
## No. repeated sample splits: 1
## Apply cross-fitting: TRUE
## 
## ------------------ Fit summary       ------------------
##  Estimates and significance testing of the effect of target variables
##             Estimate. Std. Error t value Pr(>|t|)    
## heterophily  -0.08275    0.02321  -3.565 0.000363 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
fig1 = ggplot(data = df.netIntLowDegree, 
                         aes(x = degreeD, y = homophilyC, color = avgCoopFinal*100)) + 
  geom_point() +
  scale_x_continuous("Mean degree of defectors") + 
  scale_y_continuous("C-assortativity") +  
  scale_color_viridis(option = "magma") +
  labs(color="Cooperation in \nfinal round (%)")

fig2 = ggplot(data = df.netIntLowDegree, 
                         aes(x = degreeD, y = homophilyD, color = avgCoopFinal*100)) + 
  geom_point() +
  scale_x_continuous("Mean degree of defectors") + 
  scale_y_continuous("D-assortativity") +  
  scale_color_viridis(option = "magma") +
  labs(color="Cooperation in \nfinal round (%)")

fig3 = ggplot(data = df.netIntLowDegree, 
                         aes(x = degreeD, y = heterophily, color = avgCoopFinal*100)) + 
  geom_point() +
  scale_x_continuous("Mean degree of defectors") + 
  scale_y_continuous("Heterophily") +  
  scale_color_viridis(option = "magma") +
  labs(color="Cooperation in \nfinal round (%)")

fig4 = ggplot(data = df.netIntLowDegree, 
                         aes(x = degreeC, y = homophilyC, color = avgCoopFinal*100)) + 
  geom_point() +
  scale_x_continuous("Mean degree of cooperators") + 
  scale_y_continuous("C-assortativity") +  
  scale_color_viridis(option = "magma") +
  labs(color="Cooperation in \nfinal round (%)")

fig5 = ggplot(data = df.netIntLowDegree, 
                         aes(x = degreeC, y = homophilyD, color = avgCoopFinal*100)) + 
  geom_point() +
  scale_x_continuous("Mean degree of cooperators") + 
  scale_y_continuous("D-assortativity") +  
  scale_color_viridis(option = "magma") +
  labs(color="Cooperation in \nfinal round (%)")


fig6 = ggplot(data = df.netIntLowDegree, 
                         aes(x = degreeC, y = heterophily, color = avgCoopFinal*100)) + 
  geom_point() +
  scale_x_continuous("Mean degree of cooperators") + 
  scale_y_continuous("Heterophily") +  
  scale_color_viridis(option = "magma") +
  labs(color="Cooperation in \nfinal round (%)")

fig7 = ggplot(data = df.netIntLowDegree, 
                         aes(x = degreeC, y = degreeD, color = avgCoopFinal*100)) + 
  geom_point() +
  scale_x_continuous("Mean degree of cooperators") + 
  scale_y_continuous("Mean degree of defectors") +  
  scale_color_viridis(option = "magma") +
  labs(color="Cooperation in \nfinal round (%)")

print(ggarrange(fig1,fig2,fig3,fig4,fig5,fig6,fig7,common.legend = TRUE,legend="right"))
## Warning: Removed 3 rows containing missing values (`geom_point()`).
## Removed 3 rows containing missing values (`geom_point()`).

Several explanations

Evolution of cooperation

This seems to occur regardless of initial defector/cooperator position (the same number of C's become D's, and the same number of D's become C's)